package com.jic.market.impl.coupon;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import com.jic.common.base.orm.Pagination;
import com.jic.common.base.vo.AdminOperate;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.base.vo.enums.DeptTypeEnums;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.common.utils.IDUtils;
import com.jic.member.api.rest.MessageApi;
import com.jic.member.constant.enums.MessageTypeEnum;
import com.jic.member.request.TestSendMessageRequest;
import com.jic.enums.RedisKey;
import com.jic.manager.api.manage.SysDeptApi;
import com.jic.manager.api.rest.ManagerMerchantApi;
import com.jic.manager.api.rest.ManagerStoreApi;
import com.jic.manager.request.MerchantRequest;
import com.jic.manager.response.Mestore;
import com.jic.market.common.constant.CouponConstant;
import com.jic.market.common.enums.DeleteFlagEnum;
import com.jic.market.common.enums.MerchantTypeEnum;
import com.jic.market.common.enums.MutexFlagEnum;
import com.jic.market.entity.*;
import com.jic.market.entity.base.BaseActivity;
import com.jic.market.entity.coupon.CouponConfig;
import com.jic.market.entity.coupon.CouponDetail;
import com.jic.market.entity.coupon.CouponGoods;
import com.jic.market.entity.coupon.CouponTrigger;
import com.jic.market.entity.skill.ActivityMerchantConfig;
import com.jic.market.entity.skill.ActivityStoreConfig;
import com.jic.market.enums.MarketCouponPeriodStatusEnum;
import com.jic.market.enums.MarketCouponPeriodTypeEnum;
import com.jic.market.enums.PromotionStatusEnum;
import com.jic.market.enums.PromotionTypeEnum;
import com.jic.market.mapper.*;
import com.jic.market.mapper.base.BaseActivityMapper;
import com.jic.market.mapper.coupon.CouponConfigMapper;
import com.jic.market.mapper.coupon.CouponDetailMapper;
import com.jic.market.mapper.coupon.CouponGoodsMapper;
import com.jic.market.mapper.coupon.CouponTriggerMapper;
import com.jic.market.request.*;
import com.jic.market.request.manager.base.*;
import com.jic.market.request.manager.coupon.*;
import com.jic.market.request.rest.coupon.SendCouponRequest;
import com.jic.market.response.CouponConfigQueryResponse;
import com.jic.market.response.CouponDetailResponse;
import com.jic.market.response.CouponNumAndGrouponNumResponse;
import com.jic.market.response.manager.coupon.*;
import com.jic.market.service.PromotionMemberGradeService;
import com.jic.market.service.PromotionTemplateService;
import com.jic.market.service.base.BaseActivityService;
import com.jic.market.service.coupon.CouponConfigService;
import com.jic.market.service.coupon.CouponDetailService;
import com.jic.market.service.skill.ActivityMerchantConfigService;
import com.jic.market.service.skill.ActivityStoreConfigService;
import com.jic.member.provider.service.MemberUserProviderService;
import com.jic.member.request.MememberForMarket;
import com.jic.member.response.MememberUserResponse;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.request.GoodsPageQueryRequest;
import com.jic.product.after.response.ProductStoreInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 优惠券配置表
 *
 * @author : seven
 * @version : v1.0.0
 * @email : 774329481@qq.com
 * @since : 2020-03-15 08:18:04
 */
@Slf4j
@SuppressWarnings("all")
//@Component
@Service
public class CouponConfigServiceImpl implements CouponConfigService {

    //线程池
    private static ExecutorService EXECUTORSERVICE = Executors.newFixedThreadPool(5);
    private static Integer PARTITION_NUM = 10000;

    @Autowired
    private CouponConfigMapper couponConfigMapper;

    @Autowired
    BaseActivityService baseActivityService;
    @Resource
    private BaseActivityMapper baseActivityMapper;

    @Autowired
    CouponTriggerMapper couponTriggerMapper;
    @Autowired
    ActivityMerchantConfigService activityMerchantConfigService;
    @Autowired
    ActivityStoreConfigService activityStoreConfigService;
    @Autowired
    private CouponGoodsMapper couponGoodsMapper;
    @Autowired
    CouponDetailMapper couponDetailMapper;
    @Autowired
    CouponDetailService couponDetailService;

    @Autowired
    PromotionTemplateService promotionTemplateService;

    @Autowired
    private TagMapper tagMapper;
    @Resource
    private ManagerMerchantApi managerMerchantApi;
//    @Reference(version = "${spring.profiles.active}1.0.0")
//    private MerchantService managerMerchantApi;

    @Resource
    private ManagerStoreApi mestoreService;

    @Resource
    private PromotionMerchantEntityMapper promotionMerchantEntityMapper;

    @Resource
    private PromotionMutexMapper promotionMutexMapper;

    @Resource
    private SysDeptApi sysDeptService;

    @Resource
    private MessageApi messageProviderService;

    @Resource
    private MemberUserProviderService memberUserProviderService;

    @Autowired
    private PromotionMemberGradeService promotionMemberGradeService;

    @Resource
    private MarketCouponPeriodEntityMapper marketCouponPeriodEntityMapper;

    @Resource
    private RedisClientTemplate redisClientTemplate;

    @Resource
    private ProductListApi productListApi;

    @Resource
    private PatchGrouponDetailEntityMapper patchGrouponDetailEntityMapper;



    @Override
    public long insert(CouponConfig couponConfig) {
        couponConfig.setDeleteFlag(false);
        long flag = couponConfigMapper.insert(couponConfig);
        return flag;
    }

    @Override
    public long delete(String promotionId) {
        return couponConfigMapper.delete(promotionId);
    }

    @Override
    public long update(CouponConfig couponConfig) {
        return couponConfigMapper.update(couponConfig);
    }

    @Override
    public CouponConfig queryByPrimaryKey(Long id) {
        return couponConfigMapper.queryByPrimaryKey(id);
    }

    @Override
    public List<CouponConfig> query(CouponConfig couponConfig) {
        return couponConfigMapper.query(couponConfig);
    }

    @Override
    public PageResult<CouponConfig> queryPage(CouponConfig couponConfig, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<CouponConfig> list = couponConfigMapper.queryPage(startIndex, pageQuery.getLimit(), couponConfig);
        long count = couponConfigMapper.queryPageCount(couponConfig);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public RestResult<PageResult<CouponConfigQueryResponse>> queryCouponConfigPage(CouponConfigQueryRequest request) {
        PageResult pageResult = new PageResult();

        BaseActivity activity = new BaseActivity();
        BeanUtils.copyProperties(request, activity);
        activity.setDeleteFlag(0);
        activity.setCreatorName(request.getCreator());
        activity.setDeptType(request.getAdminOperate().getDeptType().getCode());
        Page page = new Page();
        page.setStart(request.getStart());
        page.setLimit(request.getLimit());

        PageResult<BaseActivity> result = baseActivityService.queryCouponPage(activity,
                page,
                request.getMerchantId(),
                request.getStoreId(),
                request.getGrantType(),
                request.getCouponType());
        pageResult.setTotal(result.getTotal());

        if (CollectionUtils.isEmpty(result.getRows())) {
            pageResult.setRows(new ArrayList());
            return RestResult.success(pageResult);
        }

        List<CouponConfigQueryResponse> responsesList = getCouponConfigQueryResponseList(result.getRows(),request.getAdminOperate());
        pageResult.setRows(responsesList);
        return RestResult.success(pageResult);
    }

    @Override
    public RestResult<CouponConfigQueryResponse> queryCouponConfig(PromotionIdRequest promotionIdRequest) {
        CouponConfigQueryResponse response = new CouponConfigQueryResponse();
        BaseActivity baseActivity = baseActivityService.queryActivityByPromotionId(promotionIdRequest.getPromotionId());
        BeanUtils.copyProperties(baseActivity, response);

//        List<PromotionMemberGradeRequest> promotionMemberGradeRequestList = promotionMemberGradeService.queryMemberGrade(baseActivity.getPromotionId());
//        response.setPromotionMemberGradeList(promotionMemberGradeRequestList);

        response.setParentAllocationScale(baseActivity.getParentAllocationScale() == null ? "" : String.valueOf(baseActivity.getParentAllocationScale()));
        response.setChildAllocationScale(baseActivity.getChildAllocationScale() == null ? "" : String.valueOf(baseActivity.getChildAllocationScale()));
        response.setMerchantAllocationScale(baseActivity.getMerchantAllocationScale() == null ? "" : String.valueOf(baseActivity.getMerchantAllocationScale()));
        response.setStoreAllocationScale(baseActivity.getStoreAllocationScale() == null ? "" : String.valueOf(baseActivity.getStoreAllocationScale()));
        response.setChannelCodes(getArrayList(baseActivity.getChannelCodes()));
        response.setStatus(String.valueOf(baseActivity.getStatus()));
        //获取tagName
        if(StringUtils.isNotEmpty(response.getLabel())){
            Tag tag = tagMapper.queryByPrimaryKey(Long.valueOf(response.getLabel()));
            if(tag != null){
                response.setLabelName(tag.getTagName());
            }
        }
        response.setEditFlag(Long.valueOf(baseActivity.getDeptId()).equals(promotionIdRequest.getAdminOperate().getDeptId()) ? true : false);
        CouponConfig config = couponConfigMapper.queryByPromotionId(promotionIdRequest.getPromotionId());
        BeanUtils.copyProperties(config, response);
        List<String> triggerList = couponTriggerMapper.queryTriggerByPromotionIdAndTriggerType(promotionIdRequest.getPromotionId(), "0");
        response.setTriggerType(triggerList);

        List<String> patchGroupTriggerList = couponTriggerMapper.queryTriggerByPromotionIdAndTriggerType(promotionIdRequest.getPromotionId(), "1");
        response.setPatchGroupTriggerList(patchGroupTriggerList);

        List<String> speedKillTriggerList = couponTriggerMapper.queryTriggerByPromotionIdAndTriggerType(promotionIdRequest.getPromotionId(), "2");
        response.setSpeedKillTriggerList(speedKillTriggerList);
//        response.setId(promotionIdRequest.getPromotionId().toString());
        return RestResult.success(response);
    }

    private List<String> getArrayList(String param) {
        if (org.springframework.util.StringUtils.isEmpty(param)) {
            return new ArrayList<>();
        }
        String[] str = param.split(",");
        List<String> stringList = Arrays.stream(str).collect(Collectors.toList());
        return stringList;
    }

    @Override
    public RestResult<String> addCouponConfig(CouponConfigAddRequest request) {
        RestResult<String> result = new RestResult<>();
        if (request.getStartTime() != null && request.getStartTime().getTime() < System.currentTimeMillis()){
            result.setCode("5000");
            result.setMsg("活动开始时间不能小于当前时间!");
            return result;
        }
        BaseActivityRequest baseActivityRequest = new BaseActivityRequest();
        BeanUtils.copyProperties(request, baseActivityRequest);

        baseActivityRequest.setOperator(request.getAdminOperate().getOperator());
        baseActivityRequest.setOperateName(request.getAdminOperate().getOperateName());
        baseActivityRequest.setOperatorDeptId(request.getAdminOperate().getDeptId());
        result = baseActivityService.save(baseActivityRequest);
        if (!RestResult.checkIsSuccess(result)) {
            return result;
        }

        CouponConfig couponConfig = setCouponConfig(request, result.getData(), null);
        insert(couponConfig);
        return result;
    }

    @Override
    public RestResult<Boolean> updateCouponConfig(CouponConfigUpdateRequest request) {
        RestResult<Boolean> result = RestResult.success(true);
        if (request.getStartTime() != null && request.getStartTime().getTime() < new Date().getTime()){
            result.setCode("5000");
            result.setData(false);
            result.setMsg("活动开始时间不能小于当前时间!");
            return result;
        }
        BaseActivity activity = new BaseActivity();
        BeanUtils.copyProperties(request, activity);
        activity.setParentAllocationScale(request.getParentAllocationScale() == null ? 0 : request.getParentAllocationScale());
        activity.setChildAllocationScale(request.getChildAllocationScale() == null ? 0 : request.getChildAllocationScale());
        activity.setMerchantAllocationScale(request.getMerchantAllocationScale() == null ? 0 : request.getMerchantAllocationScale());
        activity.setStoreAllocationScale(request.getStoreAllocationScale() == null ? 0 : request.getStoreAllocationScale());

        long flag = baseActivityService.update(activity);

        CouponConfig config = setCouponConfig(request, request.getPromotionId(),1);
        update(config);

        MemberGradeInfoRequest memberGradeInfoRequest = new MemberGradeInfoRequest();
        memberGradeInfoRequest.setPromotionId(activity.getPromotionId());
        memberGradeInfoRequest.setPromotionCode(activity.getPromotionId());
        memberGradeInfoRequest.setPromType(Integer.parseInt(activity.getPromType()));
        memberGradeInfoRequest.setFrontPromType(Integer.parseInt(activity.getFrontPromType()));
        memberGradeInfoRequest.setPromotionMemberGradeList(request.getPromotionMemberGradeList());
        promotionMemberGradeService.updateMemberGrade(memberGradeInfoRequest);

        return result;
    }

    @Override
    public RestResult<String> copyCouponConfig(PromotionIdRequest promotionIdRequest, boolean templateFlag) {
        List<CompletableFuture<Integer>> completableFutures = new ArrayList<>();
        RestResult<String> result = baseActivityService.copy(promotionIdRequest.getPromotionId(), templateFlag);
        if (!RestResult.checkIsSuccess(result)) {
            return result;
        }

        String newPromotionId = result.getData();

        CompletableFuture<Integer> configCompletableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                long start = System.currentTimeMillis();
                copyCouponActivityConfig(promotionIdRequest, newPromotionId);
                log.info("copyCouponConfig success copyCouponActivityConfig cost = {}", System.currentTimeMillis() - start);
            } catch (Exception e) {
                log.error("copyCouponConfig copyCouponActivityConfig error", e);
            }
            return 1;
        }, EXECUTORSERVICE);
        completableFutures.add(configCompletableFuture);
//
//        if (!copyCouponActivityConfig(promotionIdRequest, newPromotionId)) {
//            return RestResult.error("9999", "复制基础配置出错");
//        }

        CompletableFuture<Integer> merchantCompletableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                long start = System.currentTimeMillis();
                activityMerchantConfigService.copyMerchant(promotionIdRequest, newPromotionId);
                log.info("copyCouponConfig success copyMerchant cost = {}", System.currentTimeMillis() - start);
            } catch (Exception e) {
                log.error("copyCouponConfig copyMerchant error", e);
            }
            return 1;
        }, EXECUTORSERVICE);
        completableFutures.add(merchantCompletableFuture);

//        if (!activityMerchantConfigService.copyMerchant(promotionIdRequest, newPromotionId)) {
//            return RestResult.error("9999", "复制商家配置出错");
//        }

        CompletableFuture<Integer> storeCompletableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                long start = System.currentTimeMillis();
                activityStoreConfigService.copyStore(promotionIdRequest, newPromotionId);
                log.info("copyCouponConfig success copyStore cost = {}", System.currentTimeMillis() - start);
            } catch (Exception e) {
                log.error("copyCouponConfig copyStore error", e);
            }
            return 1;
        }, EXECUTORSERVICE);
        completableFutures.add(storeCompletableFuture);
//        if (!activityStoreConfigService.copyStore(promotionIdRequest, newPromotionId)) {
//            return RestResult.error("9999", "复制店铺配置出错");
//        }

        CompletableFuture<Integer> triggerCompletableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                long start = System.currentTimeMillis();
                activityStoreConfigService.copyStore(promotionIdRequest, newPromotionId);
                log.info("copyCouponConfig success copyTrigger cost = {}", System.currentTimeMillis() - start);
            } catch (Exception e) {
                log.error("copyCouponConfig copyTrigger error", e);
            }
            return 1;
        }, EXECUTORSERVICE);
        completableFutures.add(triggerCompletableFuture);

//        if (!copyTrigger(promotionIdRequest, newPromotionId)) {
//            return RestResult.error("9999", "复制阶梯配置出错");
//        }

        CompletableFuture<Integer> goodsCompletableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                long start = System.currentTimeMillis();
                copyGoods(promotionIdRequest, newPromotionId);
                log.info("copyCouponConfig success copyGoods cost = {}", System.currentTimeMillis() - start);
            } catch (Exception e) {
                log.error("copyCouponConfig copyGoods error", e);
            }
            return 1;
        }, EXECUTORSERVICE);
        completableFutures.add(goodsCompletableFuture);
        CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[completableFutures.size()])).join();
//        if (!copyGoods(promotionIdRequest, newPromotionId)) {
//            return RestResult.error("9999", "复制商品配置出错");
//        }

        return RestResult.success(newPromotionId);
    }

    @Override
    public RestResult<Boolean> closeCouponConfig(PromotionIdRequest promotionIdRequest) {
        long flag = baseActivityService.updateStatusByPromotionId(promotionIdRequest.getPromotionId(),
                PromotionStatusEnum.CLOSED.getCode().toString());
        if (flag < 0) {
            return RestResult.success(true);
        }
        return RestResult.success(true);
    }

    @Override
    public RestResult<Boolean> deleteCouponConfig(PromotionIdRequest promotionIdRequest) {

        BaseActivity baseActivity = baseActivityService.queryActivityByPromotionId(promotionIdRequest.getPromotionId());

        baseActivityService.deleteByPromotionId(promotionIdRequest.getPromotionId());
        couponConfigMapper.delete(promotionIdRequest.getPromotionId());
        activityMerchantConfigService.delete(promotionIdRequest.getPromotionId());
        activityStoreConfigService.delete(promotionIdRequest.getPromotionId());
        couponTriggerMapper.delete(promotionIdRequest.getPromotionId());
        couponGoodsMapper.deleteByPromotionId(promotionIdRequest.getPromotionId());
        promotionMutexMapper.deleteListByPromotionIdAndPromType(new PromotionMutex(){{
            setPromType(PromotionTypeEnum.RED.getCode());
            setPromotionId(baseActivity.getId());
        }});
        return RestResult.success(true);
    }

    @Override
    public RestResult<Boolean> addCouponMerchantConfig(CouponMerchantAddRequest request) {
        if (CollectionUtils.isEmpty(request.getMerchantInfoList())) {
            return RestResult.success(true);
        }
        request.getMerchantInfoList().stream().forEach(temp -> {
            ActivityMerchantConfig config = new ActivityMerchantConfig();
            BeanUtils.copyProperties(temp, config);
            config.setPromotionId(request.getPromotionId());
            activityMerchantConfigService.insert(config);
        });
        return RestResult.success(true);
    }

    @Override
    public RestResult<CouponMerchantResponse> queryCouponMerchant(CouponDetailRequest promotionIdRequest) {
        //获取当前登录用户有权限的商家列表
        List<Long> merchantIds = Collections.emptyList();
        if (CollectionUtils.isNotEmpty(promotionIdRequest.getAdminOperate().getMerchantIds())){
            merchantIds = promotionIdRequest.getAdminOperate().getMerchantIds();
        }
        List<ActivityMerchantConfig> configList = activityMerchantConfigService.queryByPromotionId(promotionIdRequest.getPromotionId(),promotionIdRequest.getStart(),promotionIdRequest.getLimit(),merchantIds,promotionIdRequest);
        Long total = activityMerchantConfigService.queryByPromotionIdTotal(promotionIdRequest.getPromotionId(),merchantIds,promotionIdRequest);
        CouponMerchantResponse response = new CouponMerchantResponse();
        response.setPromotionId(promotionIdRequest.getPromotionId());

        if (CollectionUtils.isEmpty(configList)) {
            response.setMerchantInfoList(new ArrayList<>());
            return RestResult.success(response);
        }

        List<MerchantInfo> merchantInfoList = new ArrayList<>();
        configList.stream().forEach(temp -> {
            MerchantInfo merchantInfo = new MerchantInfo();
            BeanUtils.copyProperties(temp, merchantInfo);
            merchantInfoList.add(merchantInfo);
        });
        response.setTotal(total);
        response.setMerchantInfoList(merchantInfoList);
        return RestResult.success(response);
    }

    @Override
    public RestResult<Boolean> deleteCouponMerchant(MerchantDeleteRequest merchantDeleteRequest) {
        activityMerchantConfigService.deleteByPromotionIdAndMerchantId(merchantDeleteRequest.getPromotionId(),
                merchantDeleteRequest.getMerchantId());
        activityStoreConfigService.deleteStoreByPromotionIdAndMerchantId(merchantDeleteRequest.getPromotionId(),
                merchantDeleteRequest.getMerchantId());
        couponGoodsMapper.deleteGoodsByPromotionIdAndMerchantId(merchantDeleteRequest.getPromotionId(),
                merchantDeleteRequest.getMerchantId());
        return RestResult.success(true);
    }

    @Override
    public RestResult<Boolean> addCouponStoreConfig(CouponStoreAddRequest request) {
        List<StoreInfo> storeInfoList = request.getStoreInfoList();
        if (CollectionUtils.isEmpty(storeInfoList)) {
            return RestResult.success(true);
        }
        storeInfoList.stream().forEach(temp -> {
            ActivityStoreConfig activityStoreConfig = new ActivityStoreConfig();
            BeanUtils.copyProperties(temp, activityStoreConfig);
            activityStoreConfig.setPromotionId(request.getPromotionId());
            activityStoreConfigService.insert(activityStoreConfig);
        });
        return RestResult.success(true);
    }

    @Override
    public RestResult<CouponStoreResponse> queryCouponStore(CouponDetailRequest promotionIdRequest) {
        //获取当前登录用户有权限的店铺列表
        List<Long> storeIds = Collections.emptyList();
        if (CollectionUtils.isNotEmpty(promotionIdRequest.getAdminOperate().getStoreIds())){
            storeIds = promotionIdRequest.getAdminOperate().getStoreIds();
        }
        List<ActivityStoreConfig> configList = activityStoreConfigService.queryStoreByPromotionId(promotionIdRequest.getPromotionId(),promotionIdRequest.getStart(),promotionIdRequest.getLimit(),storeIds,promotionIdRequest);
        Long total = activityStoreConfigService.queryByPromotionIdTotal(promotionIdRequest.getPromotionId(),storeIds,promotionIdRequest);
        CouponStoreResponse response = new CouponStoreResponse();
        response.setPromotionId(promotionIdRequest.getPromotionId());
        if (CollectionUtils.isEmpty(configList)) {
            return RestResult.success(response);
        }

        List<StoreInfo> storeInfoList = new ArrayList<>();
        configList.stream().forEach(temp -> {
            StoreInfo storeInfo = new StoreInfo();
            BeanUtils.copyProperties(temp, storeInfo);
            log.info("查询店铺=====>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>{}",storeInfo);
            //查询店铺类型
            storeInfo.setStoreId(temp.getStoreId());
            Mestore mestore = mestoreService.queryByPrimaryKey(Long.valueOf(storeInfo.getStoreId()));
            log.info("调用manager查询店铺=====>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>{}",mestore);
            if (mestore != null){
                storeInfo.setStoreType(mestore.getStoreType());
            }
            RestResult<List<MerchantRequest>> listRestResult = managerMerchantApi.queryMerchantListByid(new ArrayList<Long>() {{
                add(mestore.getDeptId());
            }});
            storeInfo.setMerchantName(listRestResult.getData().get(0).getName());
            storeInfoList.add(storeInfo);
        });
        response.setTotal(total);
        response.setStoreInfoList(storeInfoList);
        return RestResult.success(response);
    }

    @Override
    public RestResult<Boolean> deleteCouponStore(StoreDeleteRequest storeDeleteRequest) {
        activityStoreConfigService.deleteStoreByPromotionIdAndStoreId(storeDeleteRequest.getPromotionId(),
                storeDeleteRequest.getStoreId());
        couponGoodsMapper.deleteGoodsByPromotionIdAndStoreId(storeDeleteRequest.getPromotionId(),
                storeDeleteRequest.getStoreId());
        return RestResult.success(true);
    }

    @Override
    public RestResult<Boolean> checkCoupon(CouponCheckRequest couponCheckRequest) {
        RestResult<Boolean> restResult = RestResult.success(true);
        //提交审核校验该活动下是否存在商家、店铺、商品
        //获取当前登录用户有权限的商家列表
//        List<Long> merchantIds = Collections.emptyList();
//        if (CollectionUtils.isNotEmpty(couponCheckRequest.getAdminOperate().getMerchantIds())){
//            merchantIds = couponCheckRequest.getAdminOperate().getMerchantIds();
//        }
//        //查询活动下商家
//        Long total = activityMerchantConfigService.queryByPromotionIdTotal(couponCheckRequest.getPromotionId(),merchantIds, null);
//        if (total == 0L){
//            restResult.setCode("5000");
//            restResult.setData(false);
//            restResult.setMsg("该活动下所选商家为空，请先添加商家！");
//            return restResult;
//        }
//        //获取当前登录用户有权限的店铺列表
//        List<Long> storeIds = Collections.emptyList();
//        if (CollectionUtils.isNotEmpty(couponCheckRequest.getAdminOperate().getStoreIds())){
//            storeIds = couponCheckRequest.getAdminOperate().getStoreIds();
//        }
//        //查询活动下店铺
//        Long storeTotal = activityStoreConfigService.queryByPromotionIdTotal(couponCheckRequest.getPromotionId(),storeIds,null);
//        if (storeTotal == 0L){
//            restResult.setCode("5000");
//            restResult.setData(false);
//            restResult.setMsg("该活动下所选店铺为空，请先添加店铺！");
//            return restResult;
//        }
//        //查询活动下商品
        Long goodsTotal = couponGoodsMapper.queryCouponGoodsTotal(couponCheckRequest.getPromotionId());
        if (goodsTotal == 0L){
            restResult.setCode("5000");
            restResult.setData(false);
            restResult.setMsg("该活动下所选商品为空，请先添加商品！");
            return restResult;
        }
        baseActivityService.check(couponCheckRequest.getPromotionId(),
                couponCheckRequest.getCheckRemark(),
                couponCheckRequest.getUpdateStatus());
        return restResult;
    }

    @Override
    public RestResult<Boolean> addGoodsLimit(CouponGoodsLimitIdsAddRequest couponGoodsLimitAddRequest) {
        if (CollectionUtils.isEmpty(couponGoodsLimitAddRequest.getGoodsInfoList())) {
            return RestResult.success(true);
        }

        BaseActivity baseActivityInfo = baseActivityService.queryActivityByPromotionId(couponGoodsLimitAddRequest.getPromotionId());

        couponGoodsLimitAddRequest.getGoodsInfoList().forEach(item->{
//            GoodsSpu goodsSpu = goodsSpuMapper.queryByPrimaryKey(item);
            List<ProductStoreInfo> goodsSpuList = productListApi.queryProductBySpuList(new GoodsPageQueryRequest() {{
                setId(item);
            }});
            ProductStoreInfo goodsSpu = goodsSpuList.get(0);
            //根据spuid查询Sku
//            List<GoodsSku> goodsSkus = goodsSkuMapper.query(new GoodsSku() {{
//                setGoodsSpuId(goodsSpu.getId().toString());
//            }});
            GoodsPageQueryRequest goodsPageQueryRequest = new GoodsPageQueryRequest();
            goodsPageQueryRequest.setId(item);
            List<ProductStoreInfo> productStoreInfos = productListApi.queryProductBySpuId(goodsPageQueryRequest);
            if (CollectionUtils.isEmpty(productStoreInfos)){
                log.info("add goods sku is null,spuId:{}",item);
                return;
            }
            //新增Spu
            CouponGoods activityFullnumGoodsConfig = spuSingleValue(couponGoodsLimitAddRequest.getPromotionId(), goodsSpu);
            couponGoodsMapper.insert(activityFullnumGoodsConfig);
            productStoreInfos.forEach(goodsSku -> {

                List<BaseActivity> baseActivityList = new ArrayList<>();
                if (baseActivityInfo.getPromType().equals(PromotionTypeEnum.RED.getCode().toString())){
                    baseActivityList = doMutex(couponGoodsLimitAddRequest.getPromotionId(), goodsSku.getId(), false);
                }
                CouponGoods goodsConfig = skuSingleValue(couponGoodsLimitAddRequest.getPromotionId(), goodsSku ,
                        CollectionUtils.isEmpty(baseActivityList) || !baseActivityInfo.getPromType().equals(PromotionTypeEnum.RED.getCode().toString()) ? MutexFlagEnum.UN_MUTEX : MutexFlagEnum.MUTEX , item.toString());
                couponGoodsMapper.insert(goodsConfig);
                if (CollectionUtils.isNotEmpty(baseActivityList)){
                    List<PromotionMutex> collect = baseActivityList.stream().map(baseActivity -> {
                        return new PromotionMutex().setPromotionId(baseActivity.getId())
                                .setPromType(PromotionTypeEnum.RED.getCode())
                                .setPromotionMerchantProductId(goodsConfig.getId())
                                .setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode())
                                .setCreateTime(new Date())
                                .setCreator(couponGoodsLimitAddRequest.getAdminOperate().getOperator())
                                .setCreatorName(couponGoodsLimitAddRequest.getAdminOperate().getOperateName());
                    }).collect(Collectors.toList());
                    promotionMutexMapper.insertBatch(collect);
                    //TODO 如果互斥 新增互斥记录
//                    for (BaseActivity baseActivity : baseActivityList) {
//                        promotionMutexMapper.insert(
//                                new PromotionMutex().setPromotionId(baseActivity.getId())
//                                                    .setPromType(PromotionTypeEnum.RED.getCode())
//                                                    .setPromotionMerchantProductId(goodsConfig.getId())
//                                                    .setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode())
//                                                    .setCreateTime(new Date())
//                                                    .setCreator(couponGoodsLimitAddRequest.getAdminOperate().getOperator())
//                                                    .setCreatorName(couponGoodsLimitAddRequest.getAdminOperate().getOperateName())
//                        );
//                    }
                }

            });
        });
//        couponGoodsLimitAddRequest.getGoodsInfoList().stream().forEach(temp -> {
//            CouponGoods goods = new CouponGoods();
//            BeanUtils.copyProperties(temp, goods);
//            goods.setPromotionId(couponGoodsLimitAddRequest.getPromotionId());
//            goods.setDeleteFlag(false);
//            couponGoodsMapper.insert(goods);
//        });
        return RestResult.success(true);
    }


    /**
     *
     * @param goodsId 商品编码
     * @param spuOrSku true spu false sku
     * @return
     */
    private List<BaseActivity> doMutex(String promotionId ,Long goodsId , Boolean spuOrSku){
        List<BaseActivity> baseActivityList = couponGoodsMapper.queryDoMutex(goodsId, spuOrSku);

        List<BaseActivity> mutexList = new ArrayList<>();

        if (CollectionUtils.isEmpty(baseActivityList)){
            return mutexList;
        }else{
            //判断是否存在已过期 已结束
            for (BaseActivity baseActivity : baseActivityList) {
                if ((baseActivity.getStatus().equals(PromotionStatusEnum.WAIT_SUBMIT.getCode()) ||
                        baseActivity.getStatus().equals(PromotionStatusEnum.TO_AUDIT.getCode()) ||
                        baseActivity.getStatus().equals(PromotionStatusEnum.AUDIT_NOT_PASS.getCode())) && System.currentTimeMillis() > baseActivity.getStartTime().getTime()){
                    //已过期

                }else if((baseActivity.getStatus().equals(PromotionStatusEnum.AUDIT_PASS.getCode()) || baseActivity.getStatus().equals(PromotionStatusEnum.WAIT_SUBMIT.getCode())) && baseActivity.getEndTime().getTime() < System.currentTimeMillis()){

                }else{
                    mutexList.add(baseActivity);
                }
            }
        }

        if(CollectionUtils.isEmpty(mutexList)){
            return mutexList;
        }
        //判断时间
        BaseActivity baseActivity = baseActivityService.queryActivityByPromotionId(promotionId);
        List<BaseActivity> mutexProductEntityList = new ArrayList<>();
        mutexList.stream()
                //排除自身
                .filter(i->{return !(i.getPromotionId().equals(promotionId));})
                .filter(m->{
                    return (baseActivity.getStartTime().getTime() >= m.getStartTime().getTime() &&  baseActivity.getStartTime().getTime() < m.getEndTime().getTime())
                            || (baseActivity.getEndTime().getTime() >= m.getStartTime().getTime() &&  baseActivity.getEndTime().getTime() < m.getEndTime().getTime());
                })//
                .forEach(t->{
                    mutexProductEntityList.add(t);
                });
        return mutexProductEntityList;
    }


    private CouponGoods spuSingleValue(String promotionId, ProductStoreInfo goodsSpu){
        CouponGoods goodsConfig = new CouponGoods();
        goodsConfig.setPromotionId(promotionId);
        goodsConfig.setMerchantId(goodsSpu.getMerchantId().toString());
        goodsConfig.setStoreId(goodsSpu.getStoreId().toString());
        goodsConfig.setSpuId("0");
        goodsConfig.setGoodsId(goodsSpu.getId().toString());
        goodsConfig.setGoodsName(goodsSpu.getChineseName());
        goodsConfig.setGoodsType(goodsSpu.getCategoryName());
        goodsConfig.setReserveNum(goodsSpu.getAvailableStock().toString());
        goodsConfig.setPrice(goodsSpu.getSalePriceWithTax().toString());
        goodsConfig.setMutexFlag(MutexFlagEnum.UN_MUTEX.getCode());
        return goodsConfig;
    }

    private CouponGoods skuSingleValue(String promotionId, ProductStoreInfo goodsSku , MutexFlagEnum mutexFlagEnum , String spuId){
        CouponGoods goodsConfig = new CouponGoods();
        goodsConfig.setPromotionId(promotionId);
        goodsConfig.setMerchantId(goodsSku.getMerchantId().toString());
        goodsConfig.setStoreId(goodsSku.getStoreId().toString());
        goodsConfig.setSpuId(spuId);
        goodsConfig.setGoodsId(goodsSku.getId().toString());
        goodsConfig.setGoodsName(goodsSku.getChineseName());
        goodsConfig.setGoodsType(goodsSku.getCategoryName());
        goodsConfig.setReserveNum(goodsSku.getAvailableStock().toString());
        goodsConfig.setPrice(goodsSku.getSalePriceWithTax().toString());
        goodsConfig.setMutexFlag(mutexFlagEnum.getCode());
        return goodsConfig;
    }

    private CouponGoods spuValue(String promotionId, ProductStoreInfo goodsSpu){
        CouponGoods goodsConfig = new CouponGoods();
        goodsConfig.setPromotionId(promotionId);
        goodsConfig.setMerchantId(goodsSpu.getMerchantId().toString());
        goodsConfig.setStoreId(goodsSpu.getStoreId().toString());
        goodsConfig.setSpuId("0");
        goodsConfig.setGoodsId(goodsSpu.getId().toString());
        goodsConfig.setGoodsName(goodsSpu.getChineseName());
        goodsConfig.setGoodsType(goodsSpu.getCategoryName());
        goodsConfig.setReserveNum(goodsSpu.getAvailableStock().toString());
        goodsConfig.setPrice(goodsSpu.getSalePriceWithTax().toString());
        return goodsConfig;
    }

    private CouponGoods skuValue(String promotionId, ProductStoreInfo goodsSku , String spuId, MutexFlagEnum mutexFlagEnum){
        CouponGoods goodsConfig = new CouponGoods();
        goodsConfig.setPromotionId(promotionId);
        goodsConfig.setMerchantId(goodsSku.getMerchantId().toString());
        goodsConfig.setStoreId(goodsSku.getStoreId().toString());
        goodsConfig.setSpuId(spuId);
        goodsConfig.setGoodsId(goodsSku.getId().toString());
        goodsConfig.setGoodsName(goodsSku.getChineseName());
        goodsConfig.setGoodsType(goodsSku.getCategoryName());
        goodsConfig.setReserveNum(goodsSku.getAvailableStock().toString());
        goodsConfig.setPrice(goodsSku.getSalePriceWithTax().toString());
        goodsConfig.setMutexFlag(mutexFlagEnum.getCode());
        return goodsConfig;
    }

    @Override
    public RestResult<CouponGoodsQueryResponse> queryGoodsId(PromotionIdRequest promotionIdRequest) {
        CouponGoodsQueryResponse response = new CouponGoodsQueryResponse();
        response.setPromotionId(promotionIdRequest.getPromotionId());
        if (promotionIdRequest.getStart() == null){
            promotionIdRequest.setStart(1);
        }
        if (promotionIdRequest.getLimit() == null){
            promotionIdRequest.setLimit(10);
        }
        Integer startIndex = (promotionIdRequest.getStart() - 1) * promotionIdRequest.getLimit();

        //判断查询条件是否包含商品编码
        if (promotionIdRequest.getQueryGoodsReuqest() != null && StringUtils.isNoneBlank(promotionIdRequest.getQueryGoodsReuqest().getGoodsCode())){
            //查询商品
//            List<Long> ids = goodsSpuMapper.queryIdsByTrirdSpu(promotionIdRequest.getQueryGoodsReuqest().getGoodsCode());

            List<Long> ids = productListApi.queryProductByCode(new GoodsPageQueryRequest() {{
                setGoodsCode(promotionIdRequest.getQueryGoodsReuqest().getGoodsCode());
            }});

            if(CollectionUtils.isEmpty(ids)){
                return  RestResult.success(response);
            }
            promotionIdRequest.getQueryGoodsReuqest().setGoodsCode(StringUtils.join(ids,","));
        }

        List<CouponGoods> spuList = couponGoodsMapper.queryByPromotionIdBySpu(promotionIdRequest.getPromotionId(),startIndex,promotionIdRequest.getLimit(),promotionIdRequest.getQueryGoodsReuqest());
        Long total = couponGoodsMapper.queryByPromotionIdTotalBySpu(promotionIdRequest.getPromotionId(),promotionIdRequest.getQueryGoodsReuqest());
        if (CollectionUtils.isEmpty(spuList)) {
            response.setGoodsInfoList(new ArrayList<>());
            return RestResult.success(response);
        }
        List<CouponGoodsInfo> goodsInfoList = new ArrayList<>();
        if(spuList!=null){
        spuList.stream().forEach(temp -> {
            RestResult<List<MerchantRequest>> listRestResult = managerMerchantApi.queryMerchantListByid(new ArrayList<Long>() {{
                add(Long.valueOf(temp.getMerchantId()));
            }});

            Mestore mestore = mestoreService.queryByPrimaryKey(Long.valueOf(temp.getStoreId()));

            CouponGoodsInfo couponGoodsInfo = new CouponGoodsInfo();
            BeanUtils.copyProperties(temp, couponGoodsInfo);
            if(CollectionUtils.isNotEmpty(listRestResult.getData())){
                couponGoodsInfo.setMerchantName(listRestResult.getData().get(0).getName());
            }
            if (mestore!=null){
            couponGoodsInfo.setStoreName(mestore.getStoreName());}
            couponGoodsInfo.setMpId(Long.valueOf(temp.getGoodsId()));
            //查询商品  商品库存 商品售价
            //查询spu
//            GoodsSpu goodsSpu = goodsSpuMapper.queryByPrimaryKey(Long.valueOf(couponGoodsInfo.getGoodsId()));

            List<ProductStoreInfo> goodsSpuList = productListApi.queryProductBySpuList(new GoodsPageQueryRequest() {{
                setId(Long.valueOf(couponGoodsInfo.getGoodsId()));
            }});
            ProductStoreInfo goodsSpu = goodsSpuList.get(0);

            couponGoodsInfo.setPrice(goodsSpu.getSalePriceWithTax().toString());
            couponGoodsInfo.setReserveNum(String.valueOf(goodsSpu.getAvailableStock()));
            couponGoodsInfo.setGoodsCode(goodsSpu.getCode());
            //查询 sku
            List<CouponGoods> skuList = couponGoodsMapper.query(new CouponGoods() {{
                setPromotionId(promotionIdRequest.getPromotionId());
                setSpuId(temp.getGoodsId());
                setDeleteFlag(false);
            }});
            List<CouponGoodsInfo> spuListResponse = new ArrayList<>();
            skuList.stream().forEach(sku->{
                RestResult<List<MerchantRequest>> skuMerchantList = managerMerchantApi.queryMerchantListByid(new ArrayList<Long>() {{
                    add(Long.valueOf(sku.getMerchantId()));
                }});
//                Mestore mestoreVo = mestoreService.queryByPrimaryKey(Long.valueOf(sku.getStoreId()));
                CouponGoodsInfo couponGoodsInfoSku = new CouponGoodsInfo();
                BeanUtils.copyProperties(sku,couponGoodsInfoSku);
//                couponGoodsInfoSku.setStoreName(mestoreVo.getStoreName());
                if(CollectionUtils.isNotEmpty(skuMerchantList.getData())){
                    couponGoodsInfoSku.setMerchantName(skuMerchantList.getData().get(0).getName());
                }
//                GoodsSku goodsSku = goodsSkuMapper.queryByPrimaryKey(Long.valueOf(sku.getGoodsId()));
                List<ProductStoreInfo> goodsSkuList = productListApi.queryProductBySpuList(new GoodsPageQueryRequest() {{
                    setId(Long.valueOf(sku.getGoodsId()));
                }});
                ProductStoreInfo goodsSku = goodsSkuList.get(0);
                couponGoodsInfoSku.setPrice(goodsSku.getSalePriceWithTax().toString());
                couponGoodsInfoSku.setReserveNum(String.valueOf(goodsSku.getAvailableStock()));
                couponGoodsInfoSku.setGoodsCode(goodsSku.getCode());
                couponGoodsInfoSku.setMpId(sku.getId());
                couponGoodsInfoSku.setMpParentId(Long.valueOf(temp.getGoodsId()));
                spuListResponse.add(couponGoodsInfoSku);
            });
            couponGoodsInfo.setChildren(spuListResponse);
            goodsInfoList.add(couponGoodsInfo);
        });
        }
        response.setTotal(total);
        response.setGoodsInfoList(goodsInfoList);
        //查询活动下sku数量
        Long skuTotal = couponGoodsMapper.querySkuTotalByPromotionId(promotionIdRequest.getPromotionId());
        response.setSkuTotal(skuTotal);
        return RestResult.success(response);
    }

    private void findChildren(List<CouponGoodsInfo> sysDepts, List<CouponGoodsInfo> depts) {
        for (CouponGoodsInfo sysDept : sysDepts) {
            List<CouponGoodsInfo> children = new ArrayList<>();
            for (CouponGoodsInfo dept : depts) {
                if (sysDept.getGoodsId().equals(dept.getSpuId())) {
                    children.add(dept);
                }
            }
            sysDept.setChildren(children);
            findChildren(children, depts);
        }
    }

    @Override
    public RestResult<Boolean> deleteCouponGoods(CouponGoodsDeleteRequest couponGoodsDeleteRequest) {

        List<CouponGoods> couponGoodsList = couponGoodsMapper.query(new CouponGoods() {{
            setGoodsId(couponGoodsDeleteRequest.getGoodsId());
            setPromotionId(couponGoodsDeleteRequest.getPromotionId());
            setDeleteFlag(false);
        }});
        if(CollectionUtils.isEmpty(couponGoodsList)){
            return RestResult.success(true);
        }

        //是否存在未删除的互斥商品
        AtomicBoolean mutexFlag = new AtomicBoolean(false);
        CouponGoods couponGoods = couponGoodsList.get(0);
        if ("0".equals(couponGoods.getSpuId())){
            //删除下级的sku
            List<CouponGoods> couponGoodsListSku = couponGoodsMapper.query(new CouponGoods() {{
                setSpuId(couponGoods.getGoodsId());
                setPromotionId(couponGoodsDeleteRequest.getPromotionId());
                setDeleteFlag(false);
            }});
            couponGoodsListSku.forEach(couponGoodsSku -> {
                if(MutexFlagEnum.MUTEX.getCode().equals(couponGoodsSku.getMutexFlag())&& !couponGoodsSku.getDeleteFlag()){
                    mutexFlag.set(true);
                }else{
                    couponGoodsMapper.delete(couponGoodsSku.getId());
                }
            });
        }else{
            //查询spu下的sku
            List<CouponGoods> couponGoodsSku = couponGoodsMapper.query(new CouponGoods() {{
                setPromotionId(couponGoodsDeleteRequest.getPromotionId());
                setSpuId(couponGoods.getSpuId());
                setDeleteFlag(false);
            }});
            if (CollectionUtils.isEmpty(couponGoodsSku)){
                //spu下没有sku存在 删除spu
                List<CouponGoods> couponGoodsListSpu = couponGoodsMapper.query(new CouponGoods() {{
                    setDeleteFlag(false);
                    setGoodsId(couponGoods.getSpuId());
                    setPromotionId(couponGoodsDeleteRequest.getPromotionId());
                }});
                couponGoodsListSpu.forEach(couponGoodsSpu->{
                    couponGoodsMapper.delete(couponGoodsSpu.getId());
                });
            }
        }

        if(!mutexFlag.get()){
            couponGoodsList.forEach(couponGoodsReq -> {
                couponGoodsMapper.delete(couponGoodsReq.getId());
            });
        }
//        long flag = couponGoodsMapper.deleteGoodsByPromotionIdAndGoodsId(couponGoodsDeleteRequest.getPromotionId(),
//                couponGoodsDeleteRequest.getGoodsId());
//        if (flag > 0) {
//            return RestResult.success(true);
//        }
        return RestResult.success(true);
    }

    @Override
    public RestResult<Boolean> deleteBatchGoods(CouponBatchDeleteRequest couponBatchDeleteRequest) {
        if (CollectionUtils.isEmpty(couponBatchDeleteRequest.getGoodsId())) {
            return RestResult.success(true);
        }
        couponBatchDeleteRequest.getGoodsId().stream().forEach(temp -> {
            long flag = couponGoodsMapper.deleteGoodsByPromotionIdAndGoodsId(couponBatchDeleteRequest.getPromotionId(),
                    temp);
        });
        return RestResult.success(true);
    }

    @Override
    public RestResult<Boolean> addTriggerLimit(CouponTriggerLimitAddRequest couponTriggerLimitAddRequest) {
        if (!savePageTrigger(couponTriggerLimitAddRequest.getPageTrigger(), couponTriggerLimitAddRequest.getTriggerType(), couponTriggerLimitAddRequest.getPromotionId())) {
            return RestResult.error(CouponConstant.Exception.ERROR_CODE, "保存出错");
        }
        if (!saveTriggerList(couponTriggerLimitAddRequest.getSystemTrigger(),
                couponTriggerLimitAddRequest.getTriggerType(),
                couponTriggerLimitAddRequest.getPromotionId())) {
            return RestResult.error(CouponConstant.Exception.ERROR_CODE, "保存出错");
        }
        if (!saveTriggerList(couponTriggerLimitAddRequest.getPersonTrigger(),
                couponTriggerLimitAddRequest.getTriggerType(),
                couponTriggerLimitAddRequest.getPromotionId())) {
            return RestResult.error(CouponConstant.Exception.ERROR_CODE, "保存出错");
        }
        if (!saveTriggerList(couponTriggerLimitAddRequest.getTaskTrigger(),
                couponTriggerLimitAddRequest.getTriggerType(),
                couponTriggerLimitAddRequest.getPromotionId())) {
            return RestResult.error(CouponConstant.Exception.ERROR_CODE, "保存出错");
        }
        if (!saveTriggerList(couponTriggerLimitAddRequest.getPatchGroupTriggerList(),
                CouponConstant.TriggerType.GROUP,
                couponTriggerLimitAddRequest.getPromotionId())) {
            return RestResult.error(CouponConstant.Exception.ERROR_CODE, "保存出错");
        }
        if (!saveTriggerList(couponTriggerLimitAddRequest.getSpeedKillTriggerList(),
                CouponConstant.TriggerType.SKILL,
                couponTriggerLimitAddRequest.getPromotionId())) {
            return RestResult.error(CouponConstant.Exception.ERROR_CODE, "保存出错");
        }
        String triggerNum = "";
        if (couponTriggerLimitAddRequest.getTriggerNum() == null) {
            triggerNum = "0";
        } else {
            triggerNum = Integer.toString(couponTriggerLimitAddRequest.getTriggerNum());
        }
        couponConfigMapper.updateTriggerNumByPromotionId(couponTriggerLimitAddRequest.getPromotionId(),
                triggerNum);
        return RestResult.success(true);
    }

    @Override
    public RestResult<Boolean> updateTriggerLimit(CouponTriggerLimitAddRequest couponTriggerLimitAddRequest) {
        couponTriggerMapper.delete(couponTriggerLimitAddRequest.getPromotionId());
        addTriggerLimit(couponTriggerLimitAddRequest);

        return RestResult.success(true);
    }

    @Override
    public RestResult<CouponTriggerQueryResponse> queryTrigger(PromotionIdRequest promotionIdRequest) {
        CouponTriggerQueryResponse response = new CouponTriggerQueryResponse();
        List<String> normalList = couponTriggerMapper.queryTriggerByPromotionIdAndNoTriggerType(promotionIdRequest.getPromotionId());
        response.setTriggerType(normalList);

        List<String> skillList = couponTriggerMapper.queryTriggerByPromotionIdAndTriggerType(promotionIdRequest.getPromotionId(),
                CouponConstant.TriggerType.SKILL);
        response.setSpeedKillTriggerList(skillList);

        List<String> groupList = couponTriggerMapper.queryTriggerByPromotionIdAndTriggerType(promotionIdRequest.getPromotionId(),
                CouponConstant.TriggerType.GROUP);
        response.setPatchGroupTriggerList(groupList);

        CouponConfig couponConfig = couponConfigMapper.queryByPromotionId(promotionIdRequest.getPromotionId());
        response.setTriggerNum(couponConfig.getTriggerNum());

        return RestResult.success(response);
    }

    @Override
    public RestResult<Boolean> grantCoupon(CouponGrantRequest couponGrantRequest) {
        if (CollectionUtils.isEmpty(couponGrantRequest.getMobileList()) &&
                CollectionUtils.isEmpty(couponGrantRequest.getEmailList())) {
            return RestResult.error(CouponConstant.Exception.ERROR_CODE, "手机号和邮箱不能同时为空");
        }
        if (!grantByMobile(couponGrantRequest)) {
            return RestResult.error(CouponConstant.Exception.ERROR_CODE, "通过手机号发券失败,检查余量是否超限");
        }

        if (!grantByEmail(couponGrantRequest)) {
            return RestResult.error(CouponConstant.Exception.ERROR_CODE, "通过邮箱发券失败,检查余量是否超限");
        }
        return RestResult.success(true);
    }

    @Override
    public RestResult<PageResult<CouponDetailResponse>> queryCouponDetail(CouponDetailRequest request) {
        PageResult restResult = new PageResult();

        CouponDetail couponDetail = new CouponDetail();
        couponDetail.setUseMobile(request.getUseMobile());
        couponDetail.setStatus(request.getStatus());
        couponDetail.setPromName(request.getPromName());
//        couponDetail.setPromotionId(request.getPromotionId());
        couponDetail.setPromType(request.getPromType());
        couponDetail.setCouponCode(request.getCouponCode());

        Page pageQuery = new Page();
        pageQuery.setStart(request.getStart());
        pageQuery.setLimit(request.getLimit());

        PageResult<CouponDetail> result = couponDetailService.queryPage(couponDetail, pageQuery,
                request.getCreateStartTime(),
                request.getCreateEndTime(),
                request.getUseStartTime(),
                request.getUseEndTime());

        restResult.setTotal(result.getTotal());
        List<CouponDetailResponse> responses = new ArrayList<>();
        if (CollectionUtils.isEmpty(result.getRows())) {
            restResult.setRows(responses);
            return RestResult.success(restResult);
        }

        result.getRows().stream().forEach(temp -> {

            CouponConfig couponConfig = couponConfigMapper.queryByPromotionId(temp.getPromotionId());

            CouponDetailResponse response = new CouponDetailResponse();

            response.setCouponCode(temp.getCouponCode());
            response.setUseTotalAmountLimit(couponConfig != null ? couponConfig.getUseTotalAmountLimit() : null);
            response.setCouponAmount(couponConfig != null ? couponConfig.getCouponAmount() : null);
            response.setBindTime(temp.getCreateTime());
            response.setChannelCodes(temp.getChannelCodes());
            response.setCouponUseEndTime(temp.getEndTime());
            response.setCouponUseStartTime(temp.getStartTime());
            response.setEmail(temp.getEmail());
            response.setCreateTime(temp.getCreateCouponTime());
            response.setOrderId(temp.getOrderNo());
            response.setPromName(temp.getPromName());
            response.setPromotionId(temp.getPromotionId());
            response.setStatus(temp.getStatus());
            response.setUseMobile(temp.getUseMobile());
            response.setCouponPlatform(couponConfig != null ? couponConfig.getCouponPlatform() : null);
            response.setCouponType(couponConfig != null ? couponConfig.getCouponType() : null);
            response.setAmountDeductType(couponConfig != null ? couponConfig.getAmountDeductType() : null);
            responses.add(response);
        });

        restResult.setRows(responses);

        return RestResult.success(restResult);
    }

    @Override
    public RestResult<Boolean> updateGoodsLimit(CouponGoodsLimitAddRequest couponGoodsLimitAddRequest) {
        if (CollectionUtils.isEmpty(couponGoodsLimitAddRequest.getGoodsInfoList())) {
            return RestResult.success(true);
        }
        couponGoodsLimitAddRequest.getGoodsInfoList().stream().forEach(temp -> {
            CouponGoods goodsConfig = new CouponGoods();
            BeanUtils.copyProperties(temp, goodsConfig);
            goodsConfig.setPromotionId(couponGoodsLimitAddRequest.getPromotionId());
            couponGoodsMapper.update(goodsConfig);
        });
        return RestResult.success(true);
    }

    @Override
    public RestResult<Boolean> deleteCouponDetail(PromotionIdRequest promotionIdRequest) {
        long flag = couponDetailMapper.invalidCouponDetail(promotionIdRequest.getCouponCode());
        if (flag < 0) {
            return RestResult.success(false);
        }
        return RestResult.success(true);
    }

    @Override
    public RestResult<PageResult<CouponCountResponse>> queryCouponCount(CouponCountRequest couponCountRequest) {
        PageResult pageResult = new PageResult();

        BaseActivity baseActivity = new BaseActivity();
        baseActivity.setStartTime(couponCountRequest.getStartTime());
        baseActivity.setEndTime(couponCountRequest.getEndTime());
        baseActivity.setPromotionId(couponCountRequest.getPromotionId());
        baseActivity.setPromName(couponCountRequest.getPromName());
        baseActivity.setDeleteFlag(0);
        baseActivity.setPromType(couponCountRequest.getPromType());

        Page page = new Page();
        page.setStart(couponCountRequest.getStart());
        page.setLimit(couponCountRequest.getLimit());

        PageResult<BaseActivity> result = baseActivityService.queryPage(baseActivity, page);
        pageResult.setTotal(result.getTotal());

        if (CollectionUtils.isEmpty(result.getRows())) {
            pageResult.setRows(new ArrayList());
            return RestResult.success(pageResult);
        }
        pageResult.setRows(result.getRows());

        List<CouponCountResponse> responseList = new ArrayList<>();
        result.getRows().stream().forEach(temp -> {
            CouponCountResponse response = new CouponCountResponse();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            CouponConfig config = couponConfigMapper.queryByPromotionId(temp.getPromotionId());
            Long grantNum = config.getGrantNum() == null ? 0L : config.getGrantNum();
            Long receiveNum = config.getReceiveNum() == null ? 0L : config.getReceiveNum();
            response.setGrantTotalNum(config.getGrantTotalNum()); //优惠券发行数量
            response.setNoReceiveNum(grantNum - receiveNum); //为领取的数量
            response.setReceiveNum(config.getReceiveNum()); //已领取的数量
            response.setUseNum(config.getUseNum()); // 以使用的数量
            response.setPromName(temp.getPromName()); //优惠间名称
            response.setEffectiveTime(sdf.format((config.getCouponUseStartTime()))+"-"+sdf.format(config.getCouponUseEndTime()).toString());
            response.setPromotionId(temp.getPromotionId());
            response.setId(temp.getId());
            responseList.add(response);
        });
        pageResult.setRows(responseList);

        return RestResult.success(pageResult);
    }

    @Override
    public RestResult<Boolean> addAllGoods(CouponGoodsLimitIdsAddRequest couponGoodsLimitIdsAddRequest) {
        //删除活动商品
        couponGoodsMapper.deleteGoodsByPromotionId(couponGoodsLimitIdsAddRequest.getPromotionId());

        BaseActivity baseActivity = baseActivityService.queryActivityByPromotionId(couponGoodsLimitIdsAddRequest.getPromotionId());

        //查询活动下的店铺ids
        List<String> storeIdsByPromotionId = activityStoreConfigService.queryStoreIdByPromotionId(couponGoodsLimitIdsAddRequest.getPromotionId());

        List<Long> storeIds = new ArrayList<>();

        storeIdsByPromotionId.stream().forEach(storeId->{
            storeIds.add(Long.valueOf(storeId));
        });

        //查询当前店铺下所有商品
        GoodsPageQueryRequest goodsPageQueryRequest = new GoodsPageQueryRequest();

        goodsPageQueryRequest.setStoreIds(storeIds);

        List<ProductStoreInfo> productStoreInfos = productListApi.queryProductByStoreId(goodsPageQueryRequest);

        productStoreInfos.forEach(goodsPageQueryResponse -> {
            //插入spu
            CouponGoods activityFullnumGoodsConfig = spuValue(couponGoodsLimitIdsAddRequest.getPromotionId(), goodsPageQueryResponse);
            couponGoodsMapper.insert(activityFullnumGoodsConfig);
            goodsPageQueryResponse.getChildren().forEach(skuInfo->{

                List<BaseActivity> baseActivityList = new ArrayList<>();
                if (baseActivity.getPromType().equals(PromotionTypeEnum.RED.getCode().toString())){
                    baseActivityList = doMutex(couponGoodsLimitIdsAddRequest.getPromotionId(), skuInfo.getId(), false);
                }
                CouponGoods goodsConfig = skuValue(couponGoodsLimitIdsAddRequest.getPromotionId(), skuInfo, activityFullnumGoodsConfig.getGoodsId(),
                        CollectionUtils.isEmpty(baseActivityList) || !baseActivity.getPromType().equals(PromotionTypeEnum.RED.getCode().toString()) ? MutexFlagEnum.UN_MUTEX : MutexFlagEnum.MUTEX);
                couponGoodsMapper.insert(goodsConfig);

                if (CollectionUtils.isNotEmpty(baseActivityList)){
                    //TODO 如果互斥 新增互斥记录
                    List<PromotionMutex> collect = baseActivityList.stream().map(baseActivityInfo -> {
                        return new PromotionMutex().setPromotionId(baseActivityInfo.getId())
                                .setPromType(PromotionTypeEnum.RED.getCode())
                                .setPromotionMerchantProductId(goodsConfig.getId())
                                .setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode())
                                .setCreateTime(new Date())
                                .setCreator(couponGoodsLimitIdsAddRequest.getAdminOperate().getOperator())
                                .setCreatorName(couponGoodsLimitIdsAddRequest.getAdminOperate().getOperateName());
                    }).collect(Collectors.toList());
                    promotionMutexMapper.insertBatch(collect);
//                    for (BaseActivity baseActivityInfo : baseActivityList) {
//                        promotionMutexMapper.insert(
//                                new PromotionMutex().setPromotionId(baseActivityInfo.getId())
//                                        .setPromType(PromotionTypeEnum.RED.getCode())
//                                        .setPromotionMerchantProductId(goodsConfig.getId())
//                                        .setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode())
//                                        .setCreateTime(new Date())
//                                        .setCreator(couponGoodsLimitIdsAddRequest.getAdminOperate().getOperator())
//                                        .setCreatorName(couponGoodsLimitIdsAddRequest.getAdminOperate().getOperateName())
//                        );
//                    }
                }
            });
        });

//        List<GoodsSpu> goodsSpuList = goodsSpuMapper.query(new GoodsSpu(){{
//            setDeleteFlag(false);
//        }});
//        //根据spuid查询Sku
//        goodsSpuList.forEach(goodsSpu -> {
//            List<GoodsSku> goodsSkus = goodsSkuMapper.query(new GoodsSku() {{
//                setGoodsSpuId(goodsSpu.getId().toString());
//            }});
//            //新增Spu
//            CouponGoods activityFullnumGoodsConfig = spuValue(couponGoodsLimitIdsAddRequest.getPromotionId(), goodsSpu);
//            couponGoodsMapper.insert(activityFullnumGoodsConfig);
//            goodsSkus.forEach(goodsSku -> {
//                CouponGoods goodsConfig = skuValue(couponGoodsLimitIdsAddRequest.getPromotionId(), goodsSku);
//                couponGoodsMapper.insert(goodsConfig);
//            });
//        });
        return RestResult.success(true);
    }

    @Override
    public RestResult<List<Long>> getMerchantIdsByPromotionId(PromotionIdRequest promotionIdRequest) {
        List<Long> ids = new ArrayList<>();

        if(promotionIdRequest.getGeneralPromotion()){

            List<PromotionMerchantEntity> promotionMerchantEntityList = promotionMerchantEntityMapper.findAll(new PromotionMerchantEntity() {{
                setMerchantType(MerchantTypeEnum.MERCHANT.getCode());
                setPromotionId(Long.valueOf(promotionIdRequest.getPromotionId()));
                setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
            }});
            List<Long> finalIds = new ArrayList<>();
            promotionMerchantEntityList.stream().forEach(promotionMerchantEntity -> {
                finalIds.add(promotionMerchantEntity.getMerchantId());
            });
            ids.addAll(finalIds);
        }else{
            ids = activityMerchantConfigService.queryMerchantIdsByPromotionId(promotionIdRequest.getPromotionId());
        }
        return RestResult.success(ids);
    }

    @Override
    public RestResult<List<Long>> getStoreIdsByPromotionId(PromotionIdRequest promotionIdRequest) {
        List<Long> ids = activityStoreConfigService.getStoreIdsByPromotionId(promotionIdRequest.getPromotionId());
        return RestResult.success(ids);
    }

    @Override
    public RestResult<CouponGoodsQueryResponse> queryRedGoodsByPromotionId(PromotionIdRequest promotionIdRequest) {
        CouponGoodsQueryResponse response = new CouponGoodsQueryResponse();
        response.setPromotionId(promotionIdRequest.getPromotionId());
        if (promotionIdRequest.getStart() == null){
            promotionIdRequest.setStart(1);
        }
        if (promotionIdRequest.getLimit() == null){
            promotionIdRequest.setLimit(10);
        }
        Integer startIndex = (promotionIdRequest.getStart() - 1) * promotionIdRequest.getLimit();

        //判断查询条件是否包含商品编码
        if (promotionIdRequest.getQueryGoodsReuqest() != null && StringUtils.isNoneBlank(promotionIdRequest.getQueryGoodsReuqest().getGoodsCode())){
            //查询商品
//            List<Long> ids = goodsSpuMapper.queryIdsByTrirdSpu(promotionIdRequest.getQueryGoodsReuqest().getGoodsCode());
            List<Long> ids = productListApi.queryProductByCode(new GoodsPageQueryRequest() {{
                setGoodsCode(promotionIdRequest.getQueryGoodsReuqest().getGoodsCode());
            }});
            if(CollectionUtils.isEmpty(ids)){
                return  RestResult.success(response);
            }
            promotionIdRequest.getQueryGoodsReuqest().setGoodsCode(StringUtils.join(ids,","));
        }
        List<CouponGoods> spuList = couponGoodsMapper.queryRedByPromotionIdBySpu(promotionIdRequest.getPromotionId(),promotionIdRequest.getMutexFlag(),startIndex,promotionIdRequest.getLimit(),promotionIdRequest.getQueryGoodsReuqest());
        Long total = couponGoodsMapper.queryRedByPromotionIdTotalBySpu(promotionIdRequest.getPromotionId(),promotionIdRequest.getMutexFlag(),promotionIdRequest.getQueryGoodsReuqest());
        if (CollectionUtils.isEmpty(spuList)) {
            response.setGoodsInfoList(new ArrayList<>());
            return RestResult.success(response);
        }
        List<CouponGoodsInfo> goodsInfoList = new ArrayList<>();
        spuList.stream().forEach(temp -> {
//            RestResult<List<MerchantRequest>> listRestResult = managerMerchantApi.queryMerchantListByid(new ArrayList<Long>() {{
//                add(Long.valueOf(temp.getMerchantId()));
//            }});

            Mestore mestore = mestoreService.queryByPrimaryKey(Long.valueOf(temp.getStoreId()));

            CouponGoodsInfo couponGoodsInfo = new CouponGoodsInfo();
            BeanUtils.copyProperties(temp, couponGoodsInfo);

//            if(CollectionUtils.isNotEmpty(listRestResult.getData())){
//                couponGoodsInfo.setMerchantName(listRestResult.getData().get(0).getName());
//            }
            if(null!=mestore){
                couponGoodsInfo.setStoreName(mestore.getStoreName());
            }

            couponGoodsInfo.setId(temp.getId());
            couponGoodsInfo.setMpId(Long.valueOf(temp.getGoodsId()));
            //查询商品  商品库存 商品售价
            //查询spu
//            GoodsSpu goodsSpu = goodsSpuMapper.queryByPrimaryKey(Long.valueOf(couponGoodsInfo.getGoodsId()));
            List<ProductStoreInfo> goodsSpuList = productListApi.queryProductBySpuList(new GoodsPageQueryRequest() {{
                setId(Long.valueOf(couponGoodsInfo.getGoodsId()));
            }});
            ProductStoreInfo goodsSpu = goodsSpuList.get(0);

            couponGoodsInfo.setPrice(goodsSpu.getSalePriceWithTax().toString());
            couponGoodsInfo.setReserveNum(String.valueOf(goodsSpu.getAvailableStock()));
            couponGoodsInfo.setGoodsCode(goodsSpu.getCode());
            //查询 sku
            List<CouponGoods> skuList = couponGoodsMapper.query(new CouponGoods() {{
                setPromotionId(promotionIdRequest.getPromotionId());
                setSpuId(temp.getGoodsId());
                setDeleteFlag(false);
                setMutexFlag(promotionIdRequest.getMutexFlag());
            }});
            List<CouponGoodsInfo> spuListResponse = new ArrayList<>();
            skuList.stream().forEach(sku->{
//                RestResult<List<MerchantRequest>> skuMerchantList = managerMerchantApi.queryMerchantListByid(new ArrayList<Long>() {{
//                    add(Long.valueOf(sku.getMerchantId()));
//                }});
                Mestore mestoreVo = mestoreService.queryByPrimaryKey(Long.valueOf(sku.getStoreId()));
                CouponGoodsInfo couponGoodsInfoSku = new CouponGoodsInfo();
                BeanUtils.copyProperties(sku,couponGoodsInfoSku);
                if(null!=mestoreVo){
                    couponGoodsInfoSku.setStoreName(mestoreVo.getStoreName());
                }

//                if(CollectionUtils.isNotEmpty(skuMerchantList.getData())){
//                    couponGoodsInfoSku.setMerchantName(skuMerchantList.getData().get(0).getName());
//                }
//                GoodsSku goodsSku = goodsSkuMapper.queryByPrimaryKey(Long.valueOf(sku.getGoodsId()));
                List<ProductStoreInfo> goodsSkuList = productListApi.queryProductBySpuList(new GoodsPageQueryRequest() {{
                    setId(Long.valueOf(sku.getGoodsId()));
                }});
                ProductStoreInfo goodsSku = goodsSkuList.get(0);
                couponGoodsInfoSku.setPrice(goodsSku.getSalePriceWithTax().toString());
                couponGoodsInfoSku.setReserveNum(String.valueOf(goodsSku.getAvailableStock()));
                couponGoodsInfoSku.setGoodsCode(goodsSku.getCode());
                couponGoodsInfoSku.setMpId(sku.getId());
                couponGoodsInfoSku.setMpParentId(Long.valueOf(temp.getGoodsId()));
                spuListResponse.add(couponGoodsInfoSku);
            });
            couponGoodsInfo.setChildren(spuListResponse);
            goodsInfoList.add(couponGoodsInfo);
        });
        response.setTotal(total);
        response.setGoodsInfoList(goodsInfoList);
        //查询活动下sku数量
        Long skuTotal = couponGoodsMapper.queryRedSkuTotalByPromotionId(promotionIdRequest.getPromotionId(),promotionIdRequest.getMutexFlag());
        response.setSkuTotal(skuTotal);
        return RestResult.success(response);
    }

    @Override
    public RestResult<List<Long>> getCouponStoreIdsByPromotionId(PromotionIdRequest promotionIdRequest) {
        return activityStoreConfigService.getCouponStoreIdsByPromotionId(promotionIdRequest);
    }

    @Override
    public RestResult<PageResult<CouponConfigQueryResponse>> queryRedMutexDetailPromotionList(PromotionIdRequest promotionIdRequest) {

        promotionIdRequest.setStart((promotionIdRequest.getStart() - 1) * promotionIdRequest.getLimit());
        List<CouponConfigQueryResponse> rest = promotionMutexMapper.queryRedMutexList(PromotionTypeEnum.RED.getCode().toString(),promotionIdRequest.getPromotionMerchantProductId(),
                                                                                        promotionIdRequest.getStart(),promotionIdRequest.getLimit(),
                                                                                        promotionIdRequest.getPromotionCode(),promotionIdRequest.getPromName());
        Integer count = promotionMutexMapper.queryRedMutexCount(PromotionTypeEnum.RED.getCode().toString(), promotionIdRequest.getPromotionMerchantProductId(),
                                                                promotionIdRequest.getPromotionCode(),promotionIdRequest.getPromName());

        rest.stream().forEach(couponConfigQueryResponse -> {
            RestResult<String> stringRestResult = sysDeptService.queryDeptNameById(Long.valueOf(couponConfigQueryResponse.getDeptId()));
            if(StringUtils.isNotEmpty(stringRestResult.getData())){
                couponConfigQueryResponse.setDeptName(stringRestResult.getData());
            }
        });
        return RestResult.success(new PageResult<CouponConfigQueryResponse>(){{
            setRows(rest);
            setTotal(count);
        }});
    }

    @Override
    public RestResult<Map<String, Object>> rendRedAdd(CouponGoodsLimitAddRequest couponGoodsLimitAddRequest) {

        Map<String,Object> restMap = new HashMap<>();

        List<String> restProduct = new ArrayList<>();

        BaseActivity baseActivityInfo = baseActivityService.queryActivityByPromotionId(couponGoodsLimitAddRequest.getPromotionId());

        couponGoodsLimitAddRequest.getGoodsInfoList().forEach(couponGoodsInfo -> {
            List<BaseActivity> baseActivityList = doMutex(couponGoodsLimitAddRequest.getPromotionId(), Long.valueOf(couponGoodsInfo.getGoodsId()), false);
            //删除 互斥记录
            promotionMutexMapper.deleteByPromotionProductIdAndPromType(couponGoodsInfo.getId(),PromotionTypeEnum.RED.getCode());
            if (CollectionUtils.isNotEmpty(baseActivityList)){
//                GoodsSku goodsSku = goodsSkuMapper.queryByPrimaryKey(Long.valueOf(couponGoodsInfo.getGoodsId()));

                List<ProductStoreInfo> goodsSkuList = productListApi.queryProductBySpuList(new GoodsPageQueryRequest() {{
                    setId(Long.valueOf(couponGoodsInfo.getGoodsId()));
                }});
                ProductStoreInfo goodsSku = goodsSkuList.get(0);
                restProduct.add(goodsSku.getChineseName());
                //修改当前sku互斥状态 并新增记录
                couponGoodsMapper.update(new CouponGoods(){{
                    setId(couponGoodsInfo.getId());
                    setMutexFlag(MutexFlagEnum.MUTEX.getCode());
                }});
                for (BaseActivity baseActivity : baseActivityList) {
                    promotionMutexMapper.insert(new PromotionMutex(){{
                        setPromotionMerchantProductId(couponGoodsInfo.getId());
                        setPromType(PromotionTypeEnum.RED.getCode());
                        setPromotionId(baseActivity.getId());
                        setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
                        setCreateTime(new Date());
                        setCreator(couponGoodsLimitAddRequest.getAdminOperate().getOperator());
                        setCreatorName(couponGoodsLimitAddRequest.getAdminOperate().getOperateName());
                    }});
                }
            }else{
                //重新添加 不存在互斥
                //修改当前sku的互斥状态
                couponGoodsMapper.updateMutexFlag(new CouponGoods(){{
                    setMutexFlag(MutexFlagEnum.UN_MUTEX.getCode());
                    setId(couponGoodsInfo.getId());
                }});
            }
        });
        if (CollectionUtils.isEmpty(restProduct)){
            restMap.put("businessCode", "0001");
            restMap.put("businessMsg", "商品添加成功");
        }else{
            restMap.put("businessCode", "0003");
            restMap.put("businessMsg", StringUtils.join(restProduct,"、")+"商品存在互斥活动，请在活动结束后再进行添加");
        }
        return RestResult.success(restMap);
    }

    @Override
    public PageResult<CouponConfigQueryResponse> getCouponList(CouponConfigQueryRequest couponConfigQueryRequest) {
           return baseActivityService.getCouponList(couponConfigQueryRequest);
    }


    private CouponCountResponse getCouponCountResponse(BaseActivity activity) {
        CouponCountResponse response = new CouponCountResponse();
        CouponConfig config = couponConfigMapper.queryByPromotionId(activity.getPromotionId());
        List<String> columns=new ArrayList<>();
        columns.add("key");
        columns.add("value");
        response.setColumns(columns);
        response.setPromName(activity.getPromName());

        List<CouponCountInfo> rows = new ArrayList<>();
        CouponCountInfo useInfo = setCouponCountInfo("已使用", config == null ? 0L : config.getUseNum());
        CouponCountInfo receiveInfo = setCouponCountInfo("已领取", config == null ? 0L : config.getReceiveNum());
        CouponCountInfo noReceiveInfo = setCouponCountInfo("未领取", config == null ? 0L : getNoReceiveNum(config));
        rows.add(useInfo);
        rows.add(receiveInfo);
        rows.add(noReceiveInfo);
        response.setRows(rows);
        return response;
    }

    private CouponCountInfo setCouponCountInfo(String key, Long value) {
        CouponCountInfo couponCountInfo = new CouponCountInfo();
        couponCountInfo.setKey(key);
        couponCountInfo.setValue(value);
        return couponCountInfo;
    }

    @Override
    public RestResult<String> saveTemplate(CouponTemplatRequest couponTemplatRequest) {
        PromotionIdRequest promotionIdRequest = new PromotionIdRequest();
        promotionIdRequest.setPromotionId(couponTemplatRequest.getPromotionId());
        promotionIdRequest.setAdminOperate(couponTemplatRequest.getAdminOperate());
        RestResult<String> result = copyCouponConfig(promotionIdRequest, true);
        if (!RestResult.checkIsSuccess(result)) {
            return result;
        }
        Long templateId = promotionTemplateService.saveTemplate(() -> {
            // 复制配置信息
            PromotionTemplateService.CopyResult copyResult = new PromotionTemplateService.CopyResult();
            copyResult.setPromotionId(result.getData());
            copyResult.setPromType(couponTemplatRequest.getType() == null ? PromotionTypeEnum.Coupon : PromotionTypeEnum.RED);
            copyResult.setTemplateName(couponTemplatRequest.getTemplateName());
            copyResult.setAdminOperate(couponTemplatRequest.getAdminOperate());
            return copyResult;
        });
        return RestResult.success(templateId == null ? "" : Long.toString(templateId));
    }



    @Transactional(rollbackFor = Exception.class)
    @Override
    public RestResult<Boolean> sendCoupon(SendCouponRequest couponReceiveOfPersonRequest) {
        try {
            //根据优惠券编码查询优惠券信息
            BaseActivity baseActivity = baseActivityMapper.queryByPromotionId(couponReceiveOfPersonRequest.getPromotionId());
            CouponConfig couponConfig = couponConfigMapper.queryByPromotionId(couponReceiveOfPersonRequest.getPromotionId());
            //判断优惠券是否可用
            RestResult restResult = checkCouponAvailable(baseActivity,couponConfig);
            if("0000".equals(restResult.getCode())){
                couponReceiveOfPersonRequest.getThirdUserIdList().stream().forEach(thirdUserId->{
                    CouponDetail couponDetail = new CouponDetail();
                    couponDetail.setBusinessId(Long.valueOf(baseActivity.getDeptId()));
                    couponDetail.setPromotionId(baseActivity.getPromotionId());
                    couponDetail.setPromName(baseActivity.getPromName());
                    couponDetail.setPromType(baseActivity.getPromType());
                    couponDetail.setCreateCouponTime(new Date());
                    couponDetail.setStartTime(couponConfig.getCouponUseStartTime());
                    couponDetail.setEndTime(couponConfig.getCouponUseEndTime());
                    couponDetail.setThirdUserId(thirdUserId);
                    couponDetail.setStatus(CouponConstant.CouponDetailStatus.REVICE);
                    couponDetail.setDeleteFlag(false);
                    couponDetail.setCreator(0);
                    couponDetail.setDeptId(String.valueOf(baseActivity.getDeptId()));
                    couponDetail.setCouponCode(IDUtils.GenerateBillNo());
                    long couponFlag = couponDetailMapper.insert(couponDetail);
                    //调用发送短信邮件
                    messageProviderService.branchNodeBySendMessage(couponReceiveOfPersonRequest.getTripId(),
                            couponReceiveOfPersonRequest.getBranchNodeId(), couponReceiveOfPersonRequest.getThirdUserIdList());
                });
            }else{
//                不可用 领取失败
                return restResult;
            }
            return RestResult.success(true);
        }catch (Exception e){
            log.error("发券失败===>>>>>>>>>>>>{}",e);
            return RestResult.error("9999","服务器错误, 请稍后...");
        }
    }

    @Override
    public CouponConfigQueryResponse getCouponByPromotionId(CouponConfigQueryRequest couponConfigQueryRequest) {
        return baseActivityService.getCouponByPromotionId(couponConfigQueryRequest);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RestResult<Long> backstageSendCoupon(BackstageSendCouponRequest request) {
        try {
            Long setnx = redisClientTemplate.setnx(RedisKey.COUPON_SEND_PROMOTIONID.getName()+request.getPromotionId(), "1");
            if(setnx == 0){
                return RestResult.error("9999", "当前有发放优惠券的任务正在进行，请稍后再试");
            }
            //校验手机号是否正确
            String phoneList = request.getPhoneList();
            if(StringUtils.isEmpty(phoneList)){
                redisClientTemplate.del(RedisKey.COUPON_SEND_PROMOTIONID.getName()+request.getPromotionId());
                return RestResult.error("9999","请输入手机号");
            }
            String[] phoneS = phoneList.split(",");
            // 手机号正则
            String regex = "^1[\\d]{10}";
            Boolean phoneFlag = false;
            for (int i = 0; i < phoneS.length; i++) {
                if (phoneS[i].length() != 11){
                    phoneFlag = true;
                    break;
                }
                Pattern p = Pattern.compile(regex);
                Matcher m = p.matcher(phoneS[i]);
                boolean isMatch = m.matches();
                if(!isMatch){
                    phoneFlag = true;
                    break;
                }
            }
            if(phoneFlag){
                redisClientTemplate.del(RedisKey.COUPON_SEND_PROMOTIONID.getName()+request.getPromotionId());
                return RestResult.error("9999","请输入正确格式的手机号码");
            }

            //查询活动信息
            BaseActivity baseActivity = baseActivityMapper.queryByPromotionId(request.getPromotionId());
            CouponConfig couponConfig = couponConfigMapper.queryByPromotionId(request.getPromotionId());

            //查询当前活动已发行优惠券
            List<CouponDetail> issuedList = couponDetailMapper.queryCouponByPromotionId(request.getPromotionId());

            if(couponConfig.getGrantTotalNum() != null && couponConfig.getGrantTotalNum() <= issuedList.size()){
                redisClientTemplate.del(RedisKey.COUPON_SEND_PROMOTIONID.getName()+request.getPromotionId());
                return RestResult.error("9999","已达到规定发行数量，无法继续发放");
            }
            //查询当前活动的等级限制
            List<PromotionMemberGradeRequest> promotionMemberGradeRequests = promotionMemberGradeService.queryMemberGrade(request.getPromotionId());

            //根据用户手机号获取用户第三方id
//            UccUserRequest uccUserRequest = new UccUserRequest();
//            uccUserRequest.setPhone(request.getPhoneList());
//            List<UccUserResponse> uucUserListByPhone = managerProviderService.getUccUserListByPhone(uccUserRequest);
//            log.info("UUC返回用户列表===>>>>>{}",uucUserListByPhone);
            //筛选第三方用户id不为空的
//            uucUserListByPhone = uucUserListByPhone.stream().filter(user -> user.getThridUserId() != null && !user.getThridUserId().equals("null")).collect(Collectors.toList());

//            if(CollectionUtils.isEmpty(uucUserListByPhone)){
//                redisClientTemplate.del(RedisKey.COUPON_SEND_PROMOTIONID.getName()+request.getPromotionId());
//                return RestResult.error("9999","用户不存在");
//            }

//            List<String> thridUserIdList = uucUserListByPhone.stream().map(UccUserResponse::getThridUserId).collect(Collectors.toList());
            List<MememberUserResponse> memberList = memberUserProviderService.queryMemberByPhone(request.getPhoneList());
            List<String> thridUserIdList = memberList.stream().map(MememberUserResponse::getThirdUserId).collect(Collectors.toList());

            List<Long> gradeIds = new ArrayList<>();
            for (PromotionMemberGradeRequest promotionMemberGrade: promotionMemberGradeRequests) {
                if(CollectionUtils.isEmpty(promotionMemberGrade.getLevelCodeList())){
                    continue;
                }
                List<Long> collect = promotionMemberGrade.getLevelCodeList().stream().map(m -> Long.parseLong(m.trim())).collect(Collectors.toList());
                gradeIds.addAll(collect);
            }
            String[] memType = baseActivity.getMemTypes().split(",");
            List<Long> memberTypes = Arrays.stream(memType)
                    .map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
//            //调用会员中心接口 筛选用户
            MememberForMarket mememberForMarket = new MememberForMarket();
            mememberForMarket.setMemberGradeIds(gradeIds.toArray(new Long[gradeIds.size()]));
            mememberForMarket.setMemberTypes(memberTypes.toArray(new Long[memberTypes.size()]));
            mememberForMarket.setMemThirdUserIdArr(thridUserIdList);
            RestResult<List<String>> restResult = memberUserProviderService.memberUserInfoForMarket(mememberForMarket);
            if (restResult.getCode().equals("0000")){
                //筛选用户
                List<String> userIds = restResult.getData();
                List<MememberUserResponse> restUserList = new ArrayList<>();
                memberList.forEach(uucUserInfo->{
                    boolean present = userIds.stream().filter(userId -> userId.equals(uucUserInfo.getThirdUserId())).findAny().isPresent();
                    if(present){
                        restUserList.add(uucUserInfo);
                    }
                });
                memberList = restUserList;
            }

            if(CollectionUtils.isEmpty(memberList)){
                redisClientTemplate.del(RedisKey.COUPON_SEND_PROMOTIONID.getName()+request.getPromotionId());
                return RestResult.error("9999","用户不满足活动条件限制");
            }

            //筛选用户是否拥有优惠券
            List<MememberUserResponse> sendUucUserList = new ArrayList<>();
            memberList.forEach(uucUserInfo->{
                boolean present = issuedList.stream().filter(coupon -> coupon.getThirdUserId().equals(uucUserInfo.getThirdUserId())).findAny().isPresent();
                //没有优惠券
                if(!present){
                    sendUucUserList.add(uucUserInfo);
                }
            });

            if(CollectionUtils.isEmpty(sendUucUserList)){
                redisClientTemplate.del(RedisKey.COUPON_SEND_PROMOTIONID.getName()+request.getPromotionId());
                return RestResult.error("9999","所选用户已发放优惠券,无需再次发放");
            }

            MarketCouponPeriodEntity marketCouponPeriodEntity = new MarketCouponPeriodEntity() {{
                setPromotionId(request.getPromotionId());
                setPromName(baseActivity.getPromName());
                setStatus(MarketCouponPeriodStatusEnum.IN_PROGRESS.getCode());
                setPeriodType(MarketCouponPeriodTypeEnum.BINDING.getCode());
                setSmsThirdTemplateId(request.getSmsThirdTemplateId());
                setSmsParams(request.getSmsParams());
                setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
                setCreateTime(new Date());
                setCreator(request.getAdminOperate().getOperator());
                setCreatorName(request.getAdminOperate().getOperateName());
            }};
            //新增批次
            marketCouponPeriodEntityMapper.insert(marketCouponPeriodEntity);

            //组装优惠券数据
            List<CouponDetail> couponDetailList = new ArrayList<>();

            AtomicReference<Long> cout = new AtomicReference<>(0L);

            for (MememberUserResponse uucUserInfo : sendUucUserList) {
                couponDetailList.add(new CouponDetail(){{
                    setPeriodId(marketCouponPeriodEntity.getId());
                    setCouponCode(IDUtils.GenerateBillNo());
                    setPromotionId(request.getPromotionId());
                    setPromName(baseActivity.getPromName());
                    setPromType(baseActivity.getPromType());
                    setCreateCouponTime(new Date());
                    setStartTime(couponConfig.getCouponUseStartTime());
                    setEndTime(couponConfig.getCouponUseEndTime());
                    setUseMobile(uucUserInfo.getPhone());
                    setThirdUserId(uucUserInfo.getThirdUserId());
                    setStatus(CouponConstant.CouponDetailStatus.REVICE);
                    setDeptId(String.valueOf(baseActivity.getDeptId()));
                    setDeleteFlag(false);
                }});
                cout.getAndSet(cout.get() + 1);
                if(couponConfig.getGrantTotalNum() != null && (cout.get()+issuedList.size()) >= couponConfig.getGrantTotalNum()){
                    break;
                }
            };

            //发送优惠券
            EXECUTORSERVICE.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        List<List<CouponDetail>> partitions = Lists.partition(couponDetailList, PARTITION_NUM);
                        final CountDownLatch countDownLatch = new CountDownLatch(partitions.size());

                        //延时5秒
                        Thread.sleep(5000);

                        for (List<CouponDetail> partition : partitions) {
                            couponDetailMapper.foreachInsert(partition);
                            log.info("插入优惠券记========================>?>>>>>>>>>");
                            //发送优惠券
                            try {
                                List<String> sendSmsPhoneList = partition.stream().map(CouponDetail::getUseMobile).collect(Collectors.toList());
                                TestSendMessageRequest testSendMessageRequest = new TestSendMessageRequest();
                                testSendMessageRequest.setType(MessageTypeEnum.SMS_SEND.getCode());
                                testSendMessageRequest.setParams(JSONArray.parseObject(request.getSmsParams(),Map.class));
                                testSendMessageRequest.setTestReceiver(StringUtils.join(sendSmsPhoneList,","));
                                testSendMessageRequest.setTempId(request.getSmsThirdTemplateId());
                                messageProviderService.sendTestMessage(testSendMessageRequest);
                            }catch (Exception e){
                                log.error("发送短信错误===>>>{}",e);
                            }
                        }
                        log.info("更新执行状态====>>>>>>>>>>>>>>>>>>>>>>>>>");
                        marketCouponPeriodEntityMapper.update(new MarketCouponPeriodEntity(){{
                            setId(marketCouponPeriodEntity.getId());
                            setPeriodNum(couponDetailList.size());
                            setStatus(MarketCouponPeriodStatusEnum.COMPLETED.getCode());
                            setUpdateTime(new Date());
                            setUpdator(request.getAdminOperate().getOperator());
                            setUpdatorName(request.getAdminOperate().getOperateName());
                        }});
                        redisClientTemplate.del(RedisKey.COUPON_SEND_PROMOTIONID.getName()+request.getPromotionId());
                    } catch (Exception e) {
                        log.error("生成优惠券失败===>>>>{}", e);
                        redisClientTemplate.del(RedisKey.COUPON_SEND_PROMOTIONID.getName()+request.getPromotionId());
                    }
                }
            });
            return RestResult.success(marketCouponPeriodEntity.getId());
        }catch (Exception e){
            log.error("发放优惠券错误====><>>>{}",e);
            redisClientTemplate.del(RedisKey.COUPON_SEND_PROMOTIONID.getName()+request.getPromotionId());
            return RestResult.error("9999","发放优惠券失败");
        }
    }

    @Override
    public RestResult<PageResult<MarketCouponPeriodEntity>> queryCouponPeriod(PromotionIdRequest request) {
        try{
            int startIndex = (request.getStart() - 1) * request.getLimit();
            MarketCouponPeriodEntity marketCouponPeriodEntity = new MarketCouponPeriodEntity() {{
                setPromotionId(request.getPromotionId());
                setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
            }};
            List<MarketCouponPeriodEntity> list = marketCouponPeriodEntityMapper.findOfPage(marketCouponPeriodEntity, new Pagination() {{
                setLimitStart(startIndex);
                setPageSize(request.getLimit());
            }});

            int count = marketCouponPeriodEntityMapper.countOfPage(marketCouponPeriodEntity);
            return RestResult.success(new PageResult<MarketCouponPeriodEntity>(){{
                setRows(list);
                setTotal(count);
            }});
        }catch (Exception e){
            log.error("ch查询发券记录失败哦====>>>>{}",e);
            return RestResult.error("9999","查询失败");
        }
    }

    @Override
    public RestResult<Long> getCouponIssuableTotal(PromotionIdRequest request) {
        CouponConfig couponConfig = couponConfigMapper.queryByPromotionId(request.getPromotionId());
        Long total = couponDetailMapper.queryTotalByPromotionId(request.getPromotionId(), null);
        if(couponConfig.getGrantTotalNum() == null){
            return RestResult.success(null);
        }else{
            return RestResult.success(couponConfig.getGrantTotalNum() - total);
        }
    }

    @Override
    public RestResult<Integer> queryPeriodStatusById(QueryPeriodStatusByIdRequest request) {
        MarketCouponPeriodEntity marketCouponPeriodEntity = marketCouponPeriodEntityMapper.queryById(request.getId());
        if(marketCouponPeriodEntity == null){
            return RestResult.error("9999","当前批次不存在");
        }
        return RestResult.success(marketCouponPeriodEntity.getStatus());
    }

    @Override
    public RestResult<CouponNumAndGrouponNumResponse> queryMyCouponNumberAndGrouponNumber(CouponNumAndGrouponNumRequest request) {

        //查询优惠券数
        Long couponNum = couponDetailMapper.queryMyCouponCount(request.getUserId().toString());

        Long grouponNum = patchGrouponDetailEntityMapper.queryMyGrouponCount(request.getUserId().toString());
        return RestResult.success(new CouponNumAndGrouponNumResponse(){{
            setCouponNum(couponNum);
            setGrouponNum(grouponNum);
        }});
    }


    private RestResult checkCouponAvailable(BaseActivity baseActivity, CouponConfig couponConfig) {
        if (null == baseActivity) {
            return RestResult.error("5000", "优惠券不存在, promotionId = " + baseActivity.getPromotionId());
        }
        //是否是审核通过
        if (!baseActivity.getStatus().equals(PromotionStatusEnum.AUDIT_PASS.getCode().toString())) {
            log.info("校验是否审核通过===========>>>>{}", baseActivity.getStatus());
            return RestResult.error("5001", "优惠券未通过审核, promotionId = " + baseActivity.getPromotionId());
        }
        //是否可用
        if (baseActivity.getStartTime().getTime() > System.currentTimeMillis() && couponConfig.getCouponUseStartTime().getTime() > System.currentTimeMillis()) {
            log.info("校验开始时间是否大于当前时间===========>>>>{}===>>>>>>{}", baseActivity.getStartTime().getTime(), couponConfig.getCouponUseStartTime().getTime());
            return RestResult.error("5002", "优惠券活动未开始, promotionId = " + baseActivity.getPromotionId());
        }
        if (baseActivity.getEndTime().getTime() < System.currentTimeMillis() && couponConfig.getCouponUseEndTime().getTime() < System.currentTimeMillis()) {
            log.info("校验结束时间是否小于当前时间===========>>>>{}===>>>>>>{}", baseActivity.getEndTime().getTime(), couponConfig.getCouponUseEndTime().getTime());
            return RestResult.error("5003", "优惠券活动已过期, promotionId = " + baseActivity.getPromotionId());
        }
        //发放总数
        if (null != couponConfig.getGrantTotalNum()) {
            Long total = couponDetailMapper.queryTotalByPromotionId(baseActivity.getPromotionId(), null);
            log.info("校验发放总数===========>>>>{}===>>>>>>{}", couponConfig.getGrantTotalNum(), total);
            if (Long.valueOf(couponConfig.getGrantTotalNum()) <= total) {
                return RestResult.error("5004", "优惠券数量不足, promotionId = " + baseActivity.getPromotionId());
            }
        }

        return RestResult.success("可用");
    }


    private Long getNoReceiveNum(CouponConfig config) {
        Long grantNum = config.getGrantNum() == null ? 0L : config.getGrantNum();
        Long receiveNum = config.getReceiveNum() == null ? 0L : config.getReceiveNum();
        Long noReceiveNum = grantNum - receiveNum;
        return noReceiveNum;
    }

    private boolean grantByMobile(CouponGrantRequest couponGrantRequest) {
        if (CollectionUtils.isEmpty(couponGrantRequest.getMobileList())) {
            return true;
        }
        BaseActivity activity = baseActivityService.queryActivityByPromotionId(couponGrantRequest.getPromotionId());
        if (!activity.getStatus().equals(PromotionStatusEnum.ING.getCode().toString())) {
            return false;
        }
        CouponConfig couponConfig = couponConfigMapper.queryByPromotionId(couponGrantRequest.getPromotionId());
        if (couponConfig == null) {
            return false;
        }
        Long reviceNum = couponConfig.getGrantTotalNum() - couponConfig.getGrantNum() - couponGrantRequest.getMobileList().size();
        if (reviceNum <= 0) {
            return false;
        }
        //TODO 此处逻辑 需要优化，先占用，发放失败，再回滚，或者加锁，同时只能一个人操作，防止发放过多
        AtomicInteger success = new AtomicInteger(0);
        couponGrantRequest.getMobileList().stream().forEach(temp -> {
            CouponDetail couponDetail = new CouponDetail();
            BeanUtils.copyProperties(activity, couponDetail);
            couponDetail.setPromotionId(activity.getPromotionId());
            couponDetail.setCreateCouponTime(activity.getCreateTime());
            couponDetail.setDeleteFlag(false);
            couponDetail.setOrderNo("");
            couponDetail.setEmail("");
            couponDetail.setUseMobile(temp);
            couponDetail.setStatus(CouponConstant.CouponDetailStatus.GRANT);
            couponDetail.setStartTime(couponConfig.getCouponUseStartTime());
            couponDetail.setEndTime(couponConfig.getCouponUseEndTime());
            long flag = couponDetailMapper.insert(couponDetail);
            if (flag > 0) {
                success.incrementAndGet();
            }
        });
        long falg = couponConfigMapper.updateGrantNum(couponGrantRequest.getPromotionId(), success.get());
        if (falg < 0) {
            return false;
        }
        return true;
    }

    private boolean grantByEmail(CouponGrantRequest couponGrantRequest) {
        if (CollectionUtils.isEmpty(couponGrantRequest.getEmailList())) {
            return true;
        }
        BaseActivity activity = baseActivityService.queryActivityByPromotionId(couponGrantRequest.getPromotionId());
        if (!activity.getStatus().equals(PromotionStatusEnum.ING.getCode().toString())) {
            return false;
        }
        CouponConfig couponConfig = couponConfigMapper.queryByPromotionId(couponGrantRequest.getPromotionId());
        if (couponConfig == null) {
            return false;
        }
        Long reviceNum = couponConfig.getGrantTotalNum() - couponConfig.getGrantNum() - couponGrantRequest.getMobileList().size();
        if (reviceNum <= 0) {
            return false;
        }
        //TODO 此处逻辑 需要优化，先占用，发放失败，再回滚，或者加锁，同时只能一个人操作，防止发放过多
        AtomicInteger success = new AtomicInteger(0);
        couponGrantRequest.getMobileList().stream().forEach(temp -> {
            CouponDetail couponDetail = new CouponDetail();
            BeanUtils.copyProperties(activity, couponDetail);
            couponDetail.setPromotionId(activity.getPromotionId());
            couponDetail.setCreateCouponTime(activity.getCreateTime());
            couponDetail.setDeleteFlag(false);
            couponDetail.setOrderNo("");
            couponDetail.setEmail(temp);
            couponDetail.setUseMobile("");
            couponDetail.setStatus(CouponConstant.CouponDetailStatus.GRANT);
            long flag = couponDetailMapper.insert(couponDetail);
            if (flag > 0) {
                success.incrementAndGet();
            }
        });
        long falg = couponConfigMapper.updateGrantNum(couponGrantRequest.getPromotionId(), success.get());
        if (falg < 0) {
            return false;
        }
        return true;
    }

    private boolean saveTriggerList(List<String> systemTrigger, String triggerType, String promotionId) {
        if (CollectionUtils.isEmpty(systemTrigger)) {
            return true;
        }
        //TODO triggerID应该校验的
        systemTrigger.stream().forEach(temp -> {
            CouponTrigger couponTrigger = new CouponTrigger();
            couponTrigger.setPromotionId(promotionId);
            couponTrigger.setDeleteFlag(false);
            couponTrigger.setTriggerType(triggerType);
            couponTrigger.setTriggerId(temp);
            couponTriggerMapper.insert(couponTrigger);
        });
        return true;
    }

    private boolean savePageTrigger(String pageTrigger, String triggerType, String promotionId) {
        if (StringUtils.equals(pageTrigger, CouponConstant.TriggerId.PAGE)) {
            CouponTrigger couponTrigger = new CouponTrigger();
            couponTrigger.setPromotionId(promotionId);
            couponTrigger.setDeleteFlag(false);
            couponTrigger.setTriggerType(triggerType);
            couponTrigger.setTriggerId(CouponConstant.TriggerId.PAGE);
            couponTriggerMapper.insert(couponTrigger);
        }
        return true;
    }

    private boolean copyGoods(PromotionIdRequest promotionIdRequest, String newPromotionId) {

        BaseActivity baseActivityInfo = baseActivityService.queryActivityByPromotionId(promotionIdRequest.getPromotionId());


        List<CouponGoods> goodsList = couponGoodsMapper.queryByPromotionId(promotionIdRequest.getPromotionId(), null , null);
        if (CollectionUtils.isEmpty(goodsList)) {
            return true;
        }
        goodsList.stream().forEach(temp -> {
            temp.setPromotionId(newPromotionId);
            temp.setDeleteFlag(false);
            //判断是否互斥
            List<BaseActivity> baseActivityList = new ArrayList<>();
            if(baseActivityInfo.getPromType().equals(PromotionTypeEnum.RED.getCode().toString())){
                baseActivityList = doMutex(promotionIdRequest.getPromotionId(), Long.valueOf(temp.getGoodsId()), "0".equals(temp.getSpuId()) ? true : false);
            }
            if(CollectionUtils.isNotEmpty(baseActivityList)){
                temp.setMutexFlag(MutexFlagEnum.MUTEX.getCode());
            }else{
                temp.setMutexFlag(MutexFlagEnum.UN_MUTEX.getCode());
            }
            couponGoodsMapper.insert(temp);

            if(CollectionUtils.isNotEmpty(baseActivityList)){
                List<PromotionMutex> collect = baseActivityList.stream().map(baseActivity -> {
                    return new PromotionMutex().setPromotionId(baseActivity.getId())
                            .setPromType(PromotionTypeEnum.RED.getCode())
                            .setPromotionMerchantProductId(temp.getId())
                            .setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode())
                            .setCreateTime(new Date())
                            .setCreator(promotionIdRequest.getAdminOperate().getOperator())
                            .setCreatorName(promotionIdRequest.getAdminOperate().getOperateName());
                }).collect(Collectors.toList());
                promotionMutexMapper.insertBatch(collect);
            }
        });
        return true;
    }

    private boolean copyTrigger(PromotionIdRequest promotionIdRequest, String newPromotionId) {
        List<CouponTrigger> triggerList = couponTriggerMapper.queryByPromotionId(promotionIdRequest.getPromotionId());
        if (CollectionUtils.isEmpty(triggerList)) {
            return true;
        }
        triggerList.stream().forEach(temp -> {
            temp.setPromotionId(newPromotionId);
            temp.setTriggerTypeNum("0");
            temp.setDeleteFlag(false);
            //couponTriggerMapper.insert(temp);
        });
        couponTriggerMapper.insertBatch(triggerList);
        return true;
    }

    private boolean copyCouponActivityConfig(PromotionIdRequest promotionIdRequest, String newPromotionId) {
        CouponConfig config = couponConfigMapper.queryByPromotionId(promotionIdRequest.getPromotionId());
        if (config == null) {
            return false;
        }
        config.setPromotionId(newPromotionId);
        long flag = insert(config);
        if (flag < 0) {
            return false;
        }
        return true;
    }

    private CouponConfig setCouponConfig(CouponConfigAddRequest request, String newPromotionId, Integer type) {
        CouponConfig config = new CouponConfig();
        BeanUtils.copyProperties(request, config);
        if (request.getAdminOperate().getDeptType().getCode().equals(DeptTypeEnums.OPERATION_PLATFORM.getCode()) ||
            request.getAdminOperate().getDeptType().getCode().equals(DeptTypeEnums.CHILD_PLATFORM.getCode())){
            //平台
            config.setCouponPlatform(1);
        }else{
            //店铺
            config.setCouponPlatform(2);
        }
        if(request.getGrantTotalNum() == null && type != null){
            config.setGrantTotalNum(0L);
        }
        if(request.getIdLimitNum() == null && type != null){
            config.setIdLimitNum(0L);
        }
        if(request.getIdLimitDayNum() == null && type != null){
            config.setIdLimitDayNum(0L);
        }
        config.setPromotionId(newPromotionId);
        config.setDeleteFlag(false);
        return config;
    }

    private List<CouponConfigQueryResponse> getCouponConfigQueryResponseList(List<BaseActivity> activityList, AdminOperate adminOperate) {
        if (CollectionUtils.isEmpty(activityList)) {
            return new ArrayList<>();
        }
        List<CouponConfigQueryResponse> responseList = new ArrayList<>();
        activityList.stream().forEach(temp -> {
            CouponConfigQueryResponse response = com.jic.market.common.util.BeanUtil.copy(temp,CouponConfigQueryResponse.class);
//            BeanUtil.copy(temp, response);
            CouponConfig couponConfig = couponConfigMapper.queryByPromotionId(temp.getPromotionId());
            if (null != couponConfig) {
                couponConfig.setId(null);
//                BeanUtil.copyProperties(couponConfig, response,true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
//                BeanUtil.copyProperties(couponConfig, response,true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));

                    //gradle某些情况编译出错
                                                BeanUtil.copyProperties(couponConfig, response);
//                response.setId(temp.getPromotionId());
                response.setEditFlag(Long.valueOf(temp.getDeptId()).equals(adminOperate.getDeptId()) ? true : false);
                List<String> triggerList = couponTriggerMapper.queryTriggerByPromotionIdAndNoTriggerType(temp.getPromotionId());
                response.setTriggerType(triggerList);
                List<String> patchGroupTriggerList = couponTriggerMapper.queryTriggerByPromotionIdAndTriggerType(temp.getPromotionId(), "1");
                response.setPatchGroupTriggerList(patchGroupTriggerList);
                List<String> speedKillTriggerList = couponTriggerMapper.queryTriggerByPromotionIdAndTriggerType(temp.getPromotionId(), "2");
                response.setSpeedKillTriggerList(speedKillTriggerList);
            }else{}
            responseList.add(response);
        });
        return responseList;
    }
}
